QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#785387 | #6421. Degree of Spanning Tree | lfyszy | RE | 0ms | 0kb | C++14 | 2.1kb | 2024-11-26 17:45:17 | 2024-11-26 17:45:18 |
answer
#include <bits/stdc++.h>
#define int long long
#define chmax(x, y) x = max(x, y)
#define chmin(x, y) x = min(x, y)
#define SP << " " <<
#define fish signed
using namespace std;
mt19937 rnd(1209);
const int INF = 0x3f3f3f3f3f3f3f3f;
const int N = 1e5 + 10;
vector<pair<int, int>> g;
vector<int> e[N];
int fa[N], fa1[N], d[N];
int find(int x) {return fa[x] == x ? x : fa[x] = find(fa[x]);}
set<pair<int, int>> edge;
void dfs(int u, int f)
{
fa1[u] = f; if(f) edge.insert({u, f});
for(auto v : e[u]) if(v != f) dfs(v, u);
}
void solve()
{
int n, m; cin >> n >> m;
for(int i = 1; i <= n; i ++) fa[i] = i, d[i] = 0, e[i].clear();
g.clear(); edge.clear();
for(int i = 1; i <= m; i ++)
{
int u, v; cin >> u >> v;
int fu = find(u), fv = find(v);
if(fu != fv)
{
fa[fu] = fv;
e[u].push_back(v), e[v].push_back(u);
d[u] ++, d[v] ++;
}
else g.push_back({u, v});
}
int rt = 0;
for(int i = 1; i <= n; i ++) if(d[i] > d[rt]) rt = i;
dfs(rt, 0);
for(int i = 1; i <= n; i ++) if(fa1[i] != rt) fa[i] = fa1[i]; else fa[i] = i;
for(auto x : g)
{
if(d[rt] <= n / 2) break;
int u = x.first, v = x.second;
int fu = find(u), fv = find(v);
if(fu == fv) continue;
if(d[fu] > d[fv]) swap(fu, fv), swap(u, v);
d[u] ++, d[v] ++, d[fv] --, d[rt] --; assert(v != fv);
if(d[u] + 1 > n / 2 || d[v] + 1 > n / 2) {d[u] --, d[v] --, d[fv] ++, d[rt] ++;continue;}
edge.erase({fv, rt});
edge.insert({v, u});
fa[fv] = fu;
}
rt = 0;
for(int i = 1; i <= n; i ++) if(d[i] > d[rt]) rt = i;
if(d[rt] <= n / 2)
{
cout << "Yes\n";
assert(edge.size() <= n - 1);
for(auto v : edge) cout << v.first SP v.second << "\n";
}
else cout << "No\n";
}
fish main()
{
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int t; cin >> t;
while(t --) solve();
return 0;
}
详细
Test #1:
score: 0
Runtime Error
input:
2 6 9 1 2 1 3 1 4 2 3 2 4 3 4 4 5 4 6 4 6 3 4 1 3 2 3 3 3 1 2