LA 3027 合作网络 并查集

题目链接:

https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1028

比较简单,用数组d[i]表示结点i和祖先结点的距离,查询时压缩路径并更新d[]数组。

刘汝佳大白书(P193):

贴代码:

 1 #include<cstdio>
 2 #include<algorithm>
 3 const int N = 20004;
 4 int pa[N],d[N];
 5 int findset(int x)
 6 {
 7     if(pa[x] == -1) return x;
 8     else
 9     {
10         int root = findset(pa[x]);
11         d[x] += d[pa[x]];
12         return pa[x] = root;
13     }
14 }
15 int main()
16 {
17 //    freopen("in.txt","r",stdin);
18     int t,n,u,v;
19     scanf("%d",&t);
20     while(t--)
21     {
22         scanf("%d",&n);
23         char s[4];
24         for(int i=0; i<=n; ++i) pa[i]=-1,d[i]=0;
25         while(scanf("%s",s),s[0] != 'O')
26         {
27             if(s[0] == 'E')
28             {
29                 scanf("%d",&u);
30                 findset(u);
31                 printf("%d
",d[u]);
32             }
33             else
34             {
35                 scanf("%d%d",&u,&v);
36                 pa[u] = v;
37                 d[u] = abs(u-v)%1000;
38             }
39         }
40     }
41     return 0;
42 }
View Code
原文地址:https://www.cnblogs.com/allh123/p/3287828.html