I hope you know the beautiful Union-Find structure. In this problem, you’re to implement something similar, but not identical. The data structure you need to write is also a collection of disjoint sets, supporting 3 operations:
1 p q Union the sets containing p and q. If p and q are already in the same set, ignore this command. 2 p q Move p to the set containing q. If p and q are already in the same set, ignore this command. 3 p Return the number of elements and the sum of elements in the set containing p.
Initially, the collection contains n sets: {1}, {2}, {3}, …, {n}.
Input
There are several test cases. Each test case begins with a line containing two integers n and m (1 ≤ n,m ≤ 100,000), the number of integers, and the number of commands. Each of the next m lines contains a command. For every operation, 1 ≤ p,q ≤ n. The input is terminated by end-of-file (EOF).
Output
For each type-3 command, output 2 integers: the number of elements and the sum of elements.
Explanation Initially: {1}, {2}, {3}, {4}, {5} Collection after operation 1 1 2: {1,2}, {3}, {4}, {5} Collection after operation 2 3 4: {1,2}, {3,4}, {5} (we omit the empty set that is produced when taking out 3 from {3}) Collection after operation 1 3 5: {1,2}, {3,4,5} Collection after operation 2 4 1: {1,2,4}, {3,5}
Sample Input
5 7
1 1 2
2 3 4
1 3 5
3 4
2 4 1
3 4
3 3
Sample Output
3 12
3 7
2 8
#include <iostream>
#include <cstdio>
#define MAXS 2000000
using namespace std;
int n,m;
int box[MAXS],food[MAXS],cnt[MAXS],sum[MAXS];
int opt,x,y;
int Find(int a){
if(box[a]==a)return a;
else return box[a]=Find(box[a]);
}
void Merge(int a,int b){
int fa = Find(a);
int fb =Find(b);
if(fa!=fb){
box[fa]=fb;//对应大哥连起来
sum[fb]+=sum[fa];//把对应的sum加起来
cnt[fb]+=cnt[fa];
}
}
int main(){
while(~scanf("%d %d",&n,&m)){
int t =n+1;
for(int i=1;i<=n;i++){
food[i]=i;//对应的food放在第i个box里面
box[i]=i;//Box指向自己
cnt[i]=1;//链接在一起的盒子数量
sum[i]=i;//每个集合链接的盒子当中数的sum
}
for(int i=0;i<m;i++){
scanf("%d",&opt);
if(opt==1){
scanf("%d %d",&x,&y);
Merge(food[x],food[y]);
}
else if(opt==2){
scanf("%d %d",&x,&y);
int temp = Find(food[x]);//寻找要删除结点的大哥
int ptr = Find(food[y]);
if(temp!=ptr){
cnt[temp]--;
sum[temp]-=x;
food[x]=t;
box[t]=t;
cnt[t]=1;
sum[t]=x;
t++;
Merge(food[x],food[y]);
}
}
else{
scanf("%d",&x);
int temp = Find(food[x]);
printf("%d %d\n",cnt[temp],sum[temp]);
}
}
}
return 0;
}