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
主要问题出现在2move操作,有可能移动的是根节点,只要是有儿子的节点就很麻烦。那我们怎样解决这个问题呢?
所有的问题都可以依靠再开某些记录意义的数组解决(大雾
So,我们用一个id[i]数组记录进行移动的节点的父亲的真正标号,至于p[i]本身仍然作为一个编号一个父节点留在原处。
要注意每次调用find函数时,find的变量不再是x而是id[x]!
(需要再好好理解感受一下hiahiahiahia
#include <cstdio>
const int maxnm=100010;
int n,m;
int p[maxnm],cnt[maxnm],id[maxnm]; //标记编号
long long sum[maxnm];
int c,x,y,fx,fy;
int find(int x)
{
return x==p[x]?x:p[x]=find(p[x]);
}
int main()
{
while(~scanf("%d%d",&n,&m)){
for(int i=1;i<=n;++i){
p[i]=sum[i]=id[i]=i;
cnt[i]=1;
}
for(int i=0;i<m;++i){
scanf("%d",&c);
if(c==3){
scanf("%d",&x);
fx=find(id[x]);
printf("%d %lld\n",cnt[fx],sum[fx]);
continue;
}
scanf("%d%d",&x,&y);
fx=find(id[x]);fy=find(id[y]);
if(fx==fy)
continue;
if(c==1){
p[fx]=fy;
cnt[fy]+=cnt[fx];
sum[fy]+=sum[fx];
}
else if(c==2){
--cnt[fx];
sum[fx]-=x;
id[x]=fy;
++cnt[fy];
sum[fy]+=x;
}
}
}
return 0;
}