带权并查集

Problem Description

P1196 [NOI2002]银河英雄传说

Analysis of ideas

Accepted code

#pragma GCC optimize(2)
#include <bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define pii pair<int,int>
#define gcd __gcd
const int inf = 0x3f3f3f3f;
const int maxn = 31110;
const int M = 1e9+7;
int n,m,k,ok;

int pre[maxn];
int d[maxn];
int num[maxn];      //表示第i列的飞船数量

int find(int x)
{
    if(x == pre[x]) return x;
    int k = find(pre[x]);       //k记录祖先
    d[x] += d[pre[x]];          //x的权值加上父亲的权值
    return pre[x] = k;
}

signed main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("data.in", "r", stdin);
#endif
    int T,a,b;
    cin>>T;
    char ch;
    for(int i = 1; i < maxn; i++) 
    {
        pre[i] = i;
        num[i] = 1;
    }
    while(T--)
    {
        cin>>ch>>a>>b;
        int x = find(a);
        int y = find(b);
        if(ch == 'M')
        {
            d[x] += num[y];     //x接y的后面
            pre[x] = y;
            num[y] += num[x];
            num[x] = 0;
        }
        else
        {
            if(x == y)
            {
                cout<<abs(d[a]-d[b])-1<<endl;
            }
            else
            {
                cout<<-1<<endl;
            }
            
        }
    }
    return 0;
}
posted @ 2020-01-30 09:41  hezongdnf  阅读(132)  评论(0编辑  收藏  举报