思路:大白书上的题,经典的路径压缩并且维护权值



#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 20000+500;
int fa[maxn],d[maxn];
int find(int x)
{
	if(x!=fa[x])
	{
        int root = find(fa[x]);
		d[x]+=d[fa[x]];
		return fa[x]=root;
	}
	else
		return x;
}
int main()
{
    int T;
	scanf("%d",&T);
	while(T--)
	{
		int n;
		scanf("%d",&n);
		for(int i = 1;i<=n;i++)
		{
			fa[i]=i;
			d[i]=0;
		}
		char s[2];
		while(scanf("%s",s) && s[0]!='O')
		{
             if (s[0]=='E')
			 {
				 int u;
				 scanf("%d",&u);
				 find(u);
				 printf("%d\n",d[u]);
			 }
			 else
			 {
				 int u,v;
				 scanf("%d%d",&u,&v);
				 fa[u]=v;
				 d[u]=abs(u-v)%1000;
			 }
		}
	}
}