Advertisement
GrandtherAzaMarks

DSU-НепересекающиесяМножества

Jan 27th, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. class DSU
  8. {
  9. public:
  10.     vector<int> parent;
  11.     DSU(int N)
  12.     {
  13.         parent.resize(N, -1);
  14.     }
  15.    
  16.     int find(int v)
  17.     {
  18.         int r = v;
  19.        
  20.         while (parent[r] != -1)
  21.         {
  22.             r = parent[r];
  23.         }
  24.        
  25.         while (parent[v] != -1)
  26.         {
  27.             int tmp = v;
  28.             v= parent[v];
  29.             parent[tmp] = r;
  30.         }
  31.        
  32.         return r;
  33.     }
  34.    
  35.     void unio (int i, int j)
  36.     {
  37.         int ri = find(i);
  38.         int rj = find(j);
  39.         parent[ri] = rj;
  40.     }
  41. };
  42.  
  43. int main()
  44. {
  45.     int N = 0, M = 0;
  46.     cin >> N >> M;
  47.     DSU dsu(N + 1);
  48.     int from = 0, to = 0, cnt = 0;
  49.     for (int i = 0; i < M; i++)
  50.     {
  51.         cin >> from >> to;
  52.         cnt++;
  53.         if (dsu.find(from) != dsu.find(to))
  54.         {
  55.             dsu.unio (from, to);
  56.             N--;
  57.         }
  58.         if (N == 1)
  59.             break;
  60.     }
  61.    
  62.     cout << cnt;
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement