In addition to maintaining the Father node number, each node maintains a sum value and R value, which represents the sum of the child tree (if the node is the root of the sum value is valid) and its distance to the root (that is, it has been transported several times), and then in the path compression and collection merge to maintain the two values.
1#include <iostream>2#include <cstring>3#include <cstdio>4 using namespacestd;5 6 Const intN =10001;7 intF[n];8 intSum[n];9 intR[n];Ten One voidInitintN) A { - for(inti =1; I <= N; i++ ) - { theF[i] =i; -Sum[i] =1; -R[i] =0; - } + } - + intFINDF (intx) A { at if(F[x] = = x)returnx; - inttx =findf (f[x]); -R[X] = R[x] +R[f[x]]; -F[X] =TX; - returnF[x]; - } in - voidUnion_set (intXinty) to { +x = FINDF (x), y =findf (y); - if(x = = y)return ; theF[X] =y; *Sum[y] + =Sum[x]; $r[x]++;Panax Notoginseng } - the intMain () + { A intT; thescanf"%d", &t); + for(int_case =1; _case <= t; _case++ ) - { $printf"Case %d:\n", _case); $ intN, M; -scanf"%d%d", &n, &m); - init (n); the while(m-- ) - {Wuyi Charop[2]; the intx, y; -scanf"%s", op); Wu if(op[0] =='T' ) - { Aboutscanf"%d%d", &x, &y); $ union_set (x, y); - } - Else - { Ascanf"%d", &x); + intANS1 =findf (x); the intAns2 =sum[ans1]; - intANS3 =R[x]; $printf"%d%d%d\n", Ans1, Ans2, ANS3); the } the } the } the return 0; -}
HDU 3635 and check the collection