UVALive 3027 并查集
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #include <queue> 3 #include <cstring> 4 #include <iostream> 5 #include <cstdlib> 6 #include <algorithm> 7 #include <vector> 8 #include <map> 9 #include <set> 10 #include <ctime> 11 12 using namespace std; 13 14 struct Node 15 { 16 int f,d; 17 }; 18 19 Node node[20010]; 20 int T,n,u,v; 21 22 /* 23 void findset(int x,int &d,int &f) 24 { 25 if(node[x].f==x) return; 26 findset(f,node[f].d,node[f].f); 27 d+=node[f].d; 28 f=node[f].f; 29 } 30 */ 31 32 int findset(int x) 33 { 34 if(node[x].f==x) return x; 35 int tmp=findset(node[x].f);//tmp暂时存下返回值,因为node[x].f要在node[x].d+=node[node[x].f].d后才能改变 36 node[x].d+=node[node[x].f].d; 37 return node[x].f=tmp; 38 } 39 40 int main() 41 { 42 //freopen("/home/user/桌面/in","r",stdin); 43 scanf("%d",&T); 44 while(T--) 45 { 46 scanf("%d",&n); 47 char op[2]; 48 for(int i=0;i<=20000;i++) 49 { 50 node[i].d=0; 51 node[i].f=i; 52 } 53 while(scanf("%s",op)==1&&op[0]!='O') 54 { 55 if(op[0]=='I')//I i j 56 { 57 scanf("%d%d",&u,&v); 58 node[u].f=v; 59 node[u].d+=abs(u-v)%1000; 60 //printf("%d %d\n",node[u].f,node[u].d); 61 } 62 else 63 { 64 scanf("%d",&u); 65 findset(u); 66 printf("%d\n",node[u].d); 67 //for(int i=1;i<=4;i++) 68 //printf("f=%d d=%d\n",node[i].f,node[i].d); 69 } 70 } 71 } 72 //printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC); 73 return 0; 74 }