无向图连通分量正好是一个环
作者:互联网
连通分量可以用并查集处理。
连通分量是环的条件可以是:边数等于点数,每个点的度都为2。
例题:AcWing 4493. 环形连通分量
#include<bits/stdc++.h> using namespace std; typedef long long LL; int p[200010]; int sz[200010]; int ec[200010]; bool flag[200010]; int find(int a) { if (p[a] != a) { p[a] = find(p[a]); } return p[a]; } void merge(int a, int b) { int pa = find(a); int pb = find(b); if (pa!=pb) { p[pa] = pb; sz[pb] += sz[pa]; } } void YD() { int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) { p[i] = i; sz[i] = 1; } for (int i = 1; i <= m; i++) { int a, b; cin >> a >> b; merge(a, b); ec[a]++; ec[b]++; } for (int i = 1; i <= n; i++) { int pi = find(i); if (pi != i) { ec[pi] += ec[i]; if (ec[i] != 2) flag[pi] = true; } } LL res = 0; for (int i = 1; i <= n; i++) { int pi = find(i); if (pi == i) { if (sz[i] * 2 == ec[i]&&!flag[i]) res++; } } cout << res << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int T = 1; //cin >> T; while (T--) { YD(); } return 0; }View Code
标签:连通,int,pa,200010,pb,无向,find,分量 来源: https://www.cnblogs.com/ydUESTC/p/16461741.html