First I have to say: I have poor English. I am too young, too simple, sometimes na?ve.
It was tree-planting day two weeks ago. SHENBEN dph taught us a lot about tree-planting and the disjoint sets. It was useful and valuable for a JURUO like me. I admire all SHENBENs and orz all of them!
How to plant a tree?
First of all, you should know how to make "parent arrays". It is good, isn‘t it? Using an array f[] you can put information about someone‘s father. Use f[i], i is an element‘s index, and f[i] means the father‘s index.
And we can use disjoint sets now:
- value all elements in array f[] as the index itself. It means all elements‘ father are themselves, and they any of them is a single set.
- to union two sets, use f[find(y)] = find(x); code. This means one set "tree" is the father of another.
- to see if one and another are in a set, use if (find(x) == find(y)) to determine.
But how to union sets? You can regard this method as making a tree. We can link two trees into one tree, so the question of how many continuous blocks equals the question of how many trees.
And how to find one‘s daddy ancestor? Using DFS can help a lot. If A is the father of itself, it is the top ancestor. Or, it must we can DFS its father B then (we can make the top ancestor C we found the father of A. It can save time.
Disjoint-set data structure
So it‘s simple as these codes: (LUOGU P3367 Disjoint Sets)
1 /* Luogu P3367 并查集 2 * Au: GG 3 */ 4 #include <cstdio> 5 #include <cstring> 6 #include <cmath> 7 using namespace std; 8 const int maxn = 10000 + 3; 9 int n, m, z, x, y, f[maxn]; 10 int find(int k) { // find father 11 return f[k] == k ? k : f[k] = find(f[k]); 12 } 13 int main() { 14 //freopen("p3367.in", "r", stdin); 15 scanf("%d%d", &n, &m); 16 while (n--) f[n] = n; 17 while (m--) { 18 scanf("%d%d%d", &z, &x, &y); 19 if (z == 1) { 20 f[find(y)] = find(x); 21 } else { 22 if (find(x) == find(y)) printf("Y\n"); 23 else printf("N\n"); 24 } 25 } 26 return 0; 27 }
Yes yes, it‘s quite simple at first. That‘s why we love mathematics computer science.