并差集

 1 vector<int> father;
 2 vector<int> sz;
 3 int find(int x)
 4 {
 5     if (father[x] == x)
 6         return x;
 7     else
 8         return father[x] = find(father[x]);
 9 }
10 void unionall(int x, int y)
11 {
12     int i = find(x);
13     int j = find(y);
14     if (i == j)
15         return;
16     if (sz[i] > sz[j])
17     {
18         father[j] = i;
19         sz[i] += sz[j];
20     }
21     else 
22     {
23         father[i] = j;
24         sz[j] += sz[i];
25     }
26 }
27 void init(int n)
28 {
29     father.resize(n);
30     sz.resize(n);
31     for (int i = 0; i < n; i++)
32     {
33         father[i] = i;
34         sz[i] = 1;
35     }
36 }

 

posted @ 2020-03-20 09:15  czhWellOptimized  阅读(204)  评论(0)    收藏  举报