ATC(ABC287C Path Graph?)
#include <bits/stdc++.h>
using namespace std;
struct DSU {
vector<int> f, siz;
DSU(int n) : f(n), siz(n, 1) { iota(f.begin(), f.end(), 0); }
int leader(int x) {
while (x != f[x]) x = f[x] = f[f[x]];
return x;
}
bool same(int x, int y) { return leader(x) == leader(y); }
bool merge(int x, int y) {
x = leader(x);
y = leader(y);
if (x == y) return false;
siz[x] += siz[y];
f[y] = x;
return true;
}
int size(int x) { return siz[leader(x)]; }
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N, M;
cin >> N >> M;
if (M != N - 1) {
cout << "No\n";
return 0;
}
vector<int> deg(N);
DSU dsu(N);
for (int i = 0; i < M; i++) {
int u, v;
cin >> u >> v;
// u--, v--;
deg[u]++, deg[v]++;
dsu.merge(u, v);
}
for (int i = 0; i < N; i++) {
if (deg[i] > 2) {
cout << "No\n";
return 0;
}
if (!dsu.same(i, 0)) { // 如果不连通
cout << "No\n";
return 0;
}
}
cout << "Yes\n";
return 0;
}
ATC(ABC288C Don't be cycle)
#include <bits/stdc++.h>
using namespace std;
struct DSU {
std::vector<int> f, siz;
DSU(int n) : f(n), siz(n, 1) { std::iota(f.begin(), f.end(), 0); }
int leader(int x) {
while (x != f[x]) x = f[x] = f[f[x]];
return x;
}
bool same(int x, int y) { return leader(x) == leader(y); }
bool merge(int x, int y) {
x = leader(x);
y = leader(y);
if (x == y) return false;
siz[x] += siz[y];
f[y] = x;
return true;
}
int size(int x) { return siz[leader(x)]; }
};
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n, m;
std::cin >> n >> m;
int comp = n;
DSU dsu(n);
for (int i = 0; i < m; i++) {
int u, v;
std::cin >> u >> v;
u--, v--;
comp -= dsu.merge(u, v); // comp:连通块数
}
std::cout << m - (n - comp) << "\n";
return 0;
}
标签:std,DSU,return,int,siz,查集,leader
From: https://www.cnblogs.com/LHgogo/p/17092686.html