合作网络 La3027 【并查集】
并查集 路径查询`
#include <bits/stdc++.h>
using namespace std;
const int maxn =1e5+50;
const int mod = 1e9+7;
int fa[maxn];
int edge[maxn];
int n;
void init()
{
for(int i=0;i<maxn;i++) fa[i]=i;
memset(edge,0,sizeof(edge));
}
int findset(int t)
{
if(fa[t]==t) return edge[t];
else return findset(fa[t])+edge[t];
}
void Union(int u,int v)
{
fa[u]= v;
edge[u] = abs(u-v)%1000;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
init();
scanf("%d",&n);
while(1)
{
char ch[10]; int x,y;
scanf("%s",ch);
if(ch[0]=='E')
{
scanf("%d",&x);
int ans = findset(x);
printf("%d\n",ans);
}
else if(ch[0]=='I')
{
scanf("%d%d",&x,&y);
Union(x,y);
}
else if(ch[0]=='O')
{break;}
}
}
return 0;
}
/* 1 4 E 3 I 3 1 E 3 I 1 2 E 3 I 2 4 E 3 O */