您的位置:首页 > 其它

LA3027:Corporative Network(并查集) uva 1329

2016-11-22 08:15 218 查看
题目大意:  有个很大的网络发展,现在有n个独立的结点。输入一串命令,如果是E u 就查询u到他的根结点的距离,如果是I u v,就让v做u的父节点,距离为u-v的绝对值模1000的。

题目分析:并查集问题,比较简单,在find函数里面加个counts 记录d【r】的累加。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn = 200010;
int pa[maxn],d[maxn];
int counts;
int find(int x){
counts=0;
if(pa[x] == x){
return counts;
}
else {
counts = d[x];
int r=pa[x];
while(r!=pa[r]){
counts+=d[r];
r=pa[r];
}
return counts+d[r];
}
}
int main(){
int n,t,k;
int u,v;
char sh[10],ch;
scanf("%d",&t);
while(t--){
for(int i=0;i<=maxn;i++)
pa[i]=i,d[i]=0;
scanf("%d",&n);
while(~(scanf("%s",sh))&&sh[0]!='O'){
if(sh[0] == 'E'){
scanf("%d",&u);
printf("%d\n",find(u));
}
if(sh[0] == 'I'){
scanf("%d%d",&u,&v);
pa[u]=v;
d[u] =abs(u-v)%1000;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: