加权并查集
#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>0?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=1;i<=n;i++){ fa[i]=i,d[i]=0; } char ch[9]={0}; while(scanf("%s",ch)&&ch[0]!=‘O‘){ if(ch[0]==‘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)%1000; } } } int main() { int T; scanf("%d",&T); while(T--){ solve(); } return 0; }
时间: 2024-10-14 23:59:04