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}.
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). The size of input file does not exceed 5MB.
For each type-3 command, output 2 integers: the number of elements and the sum of elements.
5 7
1 1 2
2 3 4
1 3 5
3 4
2 4 1
3 4
3 3
3 12
3 7
2 8
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}
#include
#include
const int maxn = 200010;
int fa[maxn],cnt[maxn],id[maxn];//集合,个数,编号(这个不能缺少)
long long sum[maxn];//总和
int n,m,dep;
void init()
{
for(int i = 0; i <= n; i ++)
{
sum[i] = fa[i] = id[i] = i;
cnt[i] = 1;
}
dep = n;
}
int find(int x)
{
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
void unite(int x,int y)
{
int fx = find(x);
int fy = find(y);
fa[fx] = fy;
sum[fy] += sum[fx];
cnt[fy] += cnt[fx];
}
void move(int x)
{
int fx = find(id[x]); //注意是id[x]而非x,因为一旦x点移走后,它的编号就更新了
sum[fx] -= x; //消除x节点的影响
cnt[fx] --; //同上
id[x] = ++ dep;
sum[id[x]] = x;
cnt[id[x]] = 1;
fa[id[x]] = id[x];
}
int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int op,x,y;
while (~scanf("%d%d",&n,&m))
{
init();
while(m--)
{
scanf("%d",&op);
if(op == 1)
{
scanf("%d%d",&x,&y);
if(find(id[x]) != find(id[y]))
unite(id[x],id[y]);
}
else if(op == 2)
{
scanf ("%d%d",&x,&y);
if(find(id[x])!= find (id[y]))
move(x),unite(id[x],id[y]);
}
else
{
scanf("%d",&x);
int fx = find(id[x]);
printf("%d %lld\n",cnt[fx],sum[fx]);
}
}
}
return 0;
}