Advertisement
istinishat

Disjoint Set Union

Mar 2nd, 2017
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<iostream>
  2. #include<cstdio>
  3. #include<cstring>
  4. using namespace std;
  5.  
  6. #define si(n) scanf("%d",&n)
  7. #define MAX 10004
  8.  
  9. int parent[MAX],rnk[MAX];
  10.  
  11.  
  12. void make_set (int v) {
  13.     parent[v] = v;
  14.     rnk[v] = 0;
  15. }
  16.  
  17. int find_set (int v) {
  18.     if (v == parent[v])
  19.         return v;
  20.     return parent[v] = find_set (parent[v]);
  21. }
  22.  
  23. void union_sets (int a, int b) {
  24.     a = find_set (a);
  25.     b = find_set (b);
  26.     if (a != b) {
  27.         if (rnk[a] < rnk[b])
  28.             swap (a, b);
  29.         parent[b] = a;
  30.         if (rnk[a] == rnk[b])
  31.             ++rnk[a];
  32.     }
  33. }
  34.  
  35. int main(){
  36.     int n,m,i,j;
  37.     //freopen("input.txt","r",stdin);
  38.     si(n);si(m);
  39.     for(i=1;i<=n;i++)
  40.         make_set(i);
  41.     for(i=1;i<=m;i++){
  42.         int u,v;
  43.         si(u);si(v);
  44.         union_sets(u,v);
  45.     }
  46.     for(i=1;i<=10;i++){
  47.         int u,v;
  48.         si(u);si(v);
  49.         if(find_set(u)!=find_set(v))
  50.             cout<<"Not friend"<<endl;
  51.         else cout<<"Friend"<<endl;
  52.     }
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement