Advertisement
apl-mhd

disjointSet

Apr 14th, 2018
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <iostream>
  2. #include<cstdio>
  3. #define MAX_N 101
  4. #define MAX_M 101
  5. #include <vector>
  6. #include <fstream>
  7. #include <map>
  8. using namespace std;
  9. /*
  10. save it to graph.txt file
  11. 10 7
  12. 0 1
  13. 0 2
  14. 1 2
  15. 1 3
  16. 4 5
  17. 4 6
  18. 7 8
  19.  
  20. */
  21.  
  22.  
  23. int n, m;
  24. struct  Set{
  25.  
  26.     int parent, rank;
  27.  
  28. };
  29.  
  30. struct  Edge{
  31.  
  32.     int u,v;
  33.  
  34.  
  35. };
  36.  
  37. map<int, int>mp;
  38. map<int, int>::iterator it;
  39.  
  40.  
  41. Set s[MAX_N];
  42. Edge e[MAX_M];
  43.  
  44.  
  45. void makeSet(){
  46.  
  47.     for(int i=0; i<n; i++){
  48.         s[i].parent = i;
  49.         s[i].rank = 0;
  50.  
  51.     }
  52. }
  53.  
  54. int findSet(int x){
  55.  
  56.     if(s[x].parent !=x)
  57.         return s[x].parent = findSet(s[x].parent);
  58.  
  59.     return  x;
  60.  
  61. }
  62.  
  63. void link(int u, int v){
  64.  
  65.     if(s[u].rank > s[v].rank){
  66.  
  67.         s[v].parent = u;
  68.     }
  69.     else{
  70.  
  71.       s[u].parent = v;
  72.         if(s[u].rank == s[v].rank)
  73.             s[v].rank++;
  74.  
  75.     }
  76. }
  77.  
  78. void dsUnion(int x, int y){
  79.  
  80.     int u = findSet(x);
  81.     int v = findSet(y);
  82.  
  83.     if(u !=v){
  84.  
  85.         link(u,v);
  86.     }
  87.  
  88. }
  89.  
  90.  
  91. void connectedComponent(){
  92.     makeSet();
  93.     for(int i=0; i<m; i++){
  94.  
  95.         dsUnion(e[i].u,e[i].v);
  96.     }
  97.  
  98.     for(int i=0; i<n; i++){
  99.  
  100.         mp[findSet(i)]=1;
  101.  
  102.        // cout<<i<<" "<<findSet(i)<<endl;
  103.  
  104.         //dsUnion(e[i].u,e[i].v);
  105.     }
  106.  
  107. }
  108.  
  109.  
  110. int main() {
  111.  
  112.     freopen("graph.txt", "r",stdin);
  113.  
  114.     cin>>n>>m;
  115.  
  116.     for (int i = 0; i <m ; ++i) {
  117.  
  118.         cin>>e[i].u>>e[i].v;
  119.  
  120.     }
  121.  
  122.     connectedComponent();
  123.  
  124.  
  125.     for (it = mp.begin(); it != mp.end(); it++) {
  126.  
  127.         cout<<it->first<<endl;
  128.  
  129.     }
  130.  
  131.   return 0;
  132. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement