POJ_2524(并查集模板)
POJ 2524
并查集模板题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include <iostream> using namespace std; const int maxn = 5e4+10; int pre[maxn]; int n,m; void init(int k) { for (int i=1; i<=k; i++) pre[i] = i; } int find(int x) { if (x == pre[x]) return x; return pre[x] = find(pre[x]); } void merge(int a,int b) { int ra = find(a); int rb = find(b); if (ra == rb) return; pre[ra] = rb; } int a,b; int cnt; int main() {
while (scanf("%d%d",&n,&m)) { if (n==0 && m==0) break; init(n); for (int i=1; i<=m; i++) { scanf("%d%d",&a,&b); merge(a,b); } int ans = 0; for (int i=1; i<=n; i++) if (pre[i] == i) ans++; printf("Case %d: %d\n",++cnt,ans); } return 0; }
|