giabinh

10583_UbiquitousReligions

Aug 17th, 2015
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int n, m, u, v, ans, pSet[50004];
  6. bool p[50004];
  7.  
  8. void initSet(int n) {
  9.     for (int i=0; i<=n; ++i) pSet[i] = i;
  10.     memset(p, false, sizeof(p));
  11.     ans = 0;
  12. }
  13.  
  14. int findSet(int u){
  15.     return(pSet[u] == u ? u : pSet[u] = findSet(pSet[u]));
  16. }
  17.  
  18. void unionSet(int u, int v) {
  19.     pSet[findSet(u)] = findSet(v);
  20. }
  21.  
  22. int main() {
  23.     #ifndef ONLINE_JUDGE
  24.         freopen("uva10583.inp", "r", stdin);
  25.     #endif // ONLINE_JUDGE
  26.  
  27.     int c = 0;
  28.     while (1) {
  29.         scanf("%d%d", &n, &m);
  30.         if (n == 0) break;
  31.         ++c; initSet(n);
  32.  
  33.         for (int i=0; i<m; ++i) {
  34.             scanf("%d%d", &u, &v);
  35.             unionSet(u, v);
  36.         }
  37.  
  38.         for (int i=1; i<=n; ++i)
  39.             if (!p[findSet(i)]) {
  40.                 ++ans; p[findSet(i)] = true;
  41.             }
  42.  
  43.         printf("Case %d: %d\n", c, ans);
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment