Friday, January 24, 2020

POJ.2524 Ubiquitous Religions

1.Problem
http://poj.org/problem?id=2524

2.Idea
Using data structure Union Find/Disjoint Set.

3.Source
 int Parent[50004];  
 int Size[50004];  
 int n, m;  
 void make_set(int v) {  
      Parent[v] = v;  
      Size[v] = 1;  
 }  
 int find_set(int v) {  
      if (v == Parent[v])  
           return v;  
      return Parent[v] = find_set(Parent[v]);  
 }  
 void union_sets(int a, int b) {  
      a = find_set(a);  
      b = find_set(b);  
      if (a != b) {  
           if (Size[a] < Size[b])  
                swap(a, b);  
           Parent[b] = a;  
           Size[a] += Size[b];  
      }  
 }  
 int main()  
 {  
      int t = 1;  
      while (true) {  
           scanf("%d%d", &n, &m);  
           if (n + m == 0) break;  
           for (int i = 0; i < n; i++) {  
                make_set(i);  
           }  
           for (int i = 0; i < m; i++) {  
                int x, y;  
                scanf("%d%d", &x, &y);  
                x--;  
                y--;  
                union_sets(x, y);  
           }  
           set<int> ans;  
           for (int i = 0; i < n; i++) {  
                ans.insert(find_set(i));  
           }  
           cout << "Case " << t << ": ";  
           cout << ans.size() << endl;            
           t++;  
      }  
      return 0;  
 }  

No comments:

Post a Comment