UVA1329 【Corporative Network】

N个结点,初始时每个结点的父结点都不存在。你的任务是执行一次I操作和E操作,格式如下:

  • I u v:把结点uuu的父结点设为vvv,距离为∣u−v∣mod1000|。输入保证执行指令前u没有父结点。
  • E u:询问uuu到根节点的距离。

所谓加权并查集

 1 #include<cstdio>
 2 #include<algorithm>
 3 using namespace std;
 4 const int maxn=22222;
 5 int father[maxn],d[maxn];
 6 int find(int x)
 7 {
 8     if(father[x]!=x)
 9     {
10         int zhong=find(father[x]);
11         d[x]+=d[father[x]];
12         return father[x]=zhong;
13     }
14     else return x;
15 }
16 int main()
17 {
18     int t;
19     scanf("%d",&t);
20     while(t--)
21     {
22         int n,u,v;
23         char cnm[9];
24         scanf("%d",&n);
25         for(int i=1;i<=n;++i) 
26         {
27             father[i]=i;
28             d[i]=0;
29         }
30         while(scanf("%s",cnm)&&cnm[0]!='O')
31         {
32             if(cnm[0]=='E') 
33             {
34                 scanf("%d",&u);find(u);printf("%d\n",d[u]);
35             }
36             if(cnm[0]=='I')
37             {
38                 scanf("%d%d",&u,&v);father[u]=v;d[u]=abs(u-v)%1000;
39             }
40         }
41     }
42     return 0;
43 }

猜你喜欢

转载自www.cnblogs.com/zytwan/p/9931148.html