您的位置:首页 > 其它

UVA 1329 Corporative Network(并查集)

2016-10-20 21:17 281 查看
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define ss(x) scanf("%d",&x)
const int maxn=20000+10;
int d[maxn],pa[maxn];
int n;
int getroot(int u)
{
if(pa[u]!=u) {
int root=getroot(pa[u]);
d[u]+=d[pa[u]];
return pa[u]=root;
}
else return u;
}
int main()
{
int t;
ss(t);
while(t--)
{
ss(n);
rep(i,1,n) {pa[i]=i;d[i]=0;}
char cmd[10];
while(scanf("%s",cmd)&&cmd[0]!='O')
{
int x,y;
if(cmd[0]=='I') {
ss(x);ss(y);
pa[x]=y;
d[x]=abs(x-y)%1000;
}
if(cmd[0]=='E'){
ss(x);
getroot(x);
cout<<d[x]<<endl;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: