UVALive - 3027:Corporative Network

加权并查集

#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#define MAXN 20000+10
#define pii pair<int,int>
using namespace std;
int fa[MAXN];
int d[MAXN];
int n;
int Abs(int x){
return (x>?x:-x);
}
pii find(int x){
if(fa[x]!=x){
pii t=find(fa[x]);
fa[x]=t.first;
d[x]+=t.second;
}
return make_pair(fa[x],d[x]);
}
void solve(){
scanf("%d",&n);
for(int i=;i<=n;i++){
fa[i]=i,d[i]=;
}
char ch[]={};
while(scanf("%s",ch)&&ch[]!='O'){
if(ch[]=='E'){
int x;
scanf("%d",&x);
printf("%d\n",find(x).second);
}
else{
int x,y;
scanf("%d%d",&x,&y);
fa[x]=y;
d[x]=Abs(x-y)%;
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
solve();
}
return ;
}
上一篇:用Python编写的第一个回测程序


下一篇:MySQL冗余和重复索引