通过这道题,对并查集的查找又有了一定的认识,初步理解了路径压缩的好处,这里,根结点的转移次数不是直接加上根结点的移动次数,而是在路径压缩的过程中逐层累加,比如有4层,根结点为1,然后第二层2,第三层3,第四层4.那么,第一层路径压缩过程中进入第二层,然后第三层,然后第四层,第四层也就是根,找到根结点,返回第三层,第三层+上第四层的转移次数,然后返回第二层,第二层转移次数加上第三层转移次数,返回第一层,第一层转移次数加上第二层转移次数,同时,在这个过程中也把下面3层的结点的父节点直接更新为和根结点,也就是1相连,查找结束后,称为2层结构,根结点1在一层,234都处于第二层。这样的一个过程是通过递归调用本身完成的,跟数据结构(严蔚敏版本)讲解栈那节的汉诺塔过程相似,如果想完全掌握,推荐仔细看教材+自己模拟,这样就可以理解了。。。。。
代码如下:
- #include<iostream>
- #include<cstdio>
- #include<cstring>
- #include<algorithm>
- using namespace std;
- #define N 10010
- struct node
- {
- int parent; //根节点
- int son; //子节点
- int transport; //转移次数
- }p[N];
- int find(int x)
- {
- int temp;
- if(x == p[x].parent)
- return x;
- else
- {
- temp = p[x].parent;
- p[x].parent = find(p[x].parent);
- p[x].transport += p[temp].transport; //这点需要反复揣摩
- }
- return p[x].parent;
- }
- void join(int x, int y)
- {
- int root1, root2;
- root1 = find(x);
- root2 = find(y);
- if(root1 == root2)
- return ;
- p[root1].parent = root2;
- p[root1].transport++; //根节点转移次数+1,要理解
- p[root2].son += p[root1].son;
- p[root1].son = 0;
- }
- int main()
- {
- int ncase, T = 1;
- int num, querynum;
- char ope;
- int from, to;
- int querycity;
- int ans;
- scanf("%d", &ncase);
- while(ncase--)
- {
- scanf("%d%d", &num, &querynum);
- for(int i = 1; i <= num; ++i) //初始化
- {
- p[i].parent = i;
- p[i].son = 1;
- p[i].transport = 0;
- }
- printf("Case %d:\n", T++);
- for(int i = 0; i < querynum; ++i)
- {
- scanf("%*c%c", &ope);
- if(ope == 'T')
- {
- scanf("%d%d", &from, &to);
- join(from, to);
- }
- else
- {
- scanf("%d", &querycity);
- ans = find(querycity);
- printf("%d %d %d\n", ans, p[ans].son, p[querycity].transport); //纠结了3个小时~~
- }
- }
- }
- return 0;
- }