并查集

Almost Union-Find

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). The size of input file does not exceed 5MB.

Output

For each type-3 command, output 2 integers: the number of elements and the sum of elements.

Sample Input

5 7
1 1 2
2 3 4
1 3 5
3 4
2 4 1
3 4
3 3

Output for the Sample Input

3 12
3 7
2 8

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}

此题关键在于删除一个元素,删除后我们重新建一个集合,重新合并求解即可。

 

#include
#include
#include
using namespace std;
#define maxn 100005
int father[maxn];//父节点
int num[maxn];//记录的是集合的元素个数
int idx[maxn];//所属集合的编号
long long sum[maxn];//元素的和
int cnt,n,m;
int find(int x)
{
    if(father[x]==x)
    return x;
    else
    return father[x]=find(father[x]);
}

void Union(int x,int y)
{
    int tx=find(idx[x]);
    int ty=find(idx[y]);
    father[tx]=ty;
    num[ty]+=num[tx];
    sum[ty]+=sum[tx];
}

void Delete(int x)
{
    int tx=idx[x];
    sum[find(tx)]-=x;//和少x
    num[find(tx)]--;//个数减少一个
    idx[x]=++cnt;//删除后属于一个新的集合
    sum[idx[x]]=x;//新集合一个元素
    num[idx[x]]=1;
    father[idx[x]]=idx[x];
}
void init()
{
    for(int i=0;i<=n;i++)
    {
        sum[i]=idx[i]=father[i]=i;
        num[i]=1;
    }
    cnt=n;
}
int main()
{
    int a,b,c;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        init();
        for(int i=0;i>a;
            if(a==1)
            {
                cin>>b>>c;
                if(find(idx[b])!=find(idx[c]))
                {
                    Union(b,c);
                }
            }
            else if(a==2)
            {
                cin>>b>>c;
                if(find(idx[b])!=find(idx[c]))
                {
                    Delete(b);
                    Union(b,c);
                }
            }
            else if(a==3)
            {
                cin>>b;
                cout<


你可能感兴趣的:(并查集)