UVALive - 3027:Corporative Network

时间:2024-06-03 09:04:14

加权并查集

#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 ;
}