AcWing 238. 银河英雄传说(并查集)

题目链接

活动 - AcWing本活动组织刷《算法竞赛进阶指南》,系统学习各种编程算法。主要面向有一定编程基础的同学。icon-default.png?t=N7T8https://www.acwing.com/problem/content/240/

代码

#include 
#include 
#include 
#include 

using namespace std;

const int N = 30010;

int m;
int p[N], sz[N], d[N];

int find(int x)
{
    if (p[x] != x)
    {
        int root = find(p[x]);
        d[x] += d[p[x]];
        p[x] = root;
    }
    return p[x];
}

int main()
{
    scanf("%d", &m);
    
    for (int i = 1; i < N; i++)
    {
        p[i] = i;
        sz[i] = 1;
    }
    
    while (m--)
    {
        char op[2];
        int a, b;
        scanf("%s%d%d", op, &a, &b);
        if (op[0] == 'M')
        {
            int pa = find(a), pb = find(b);
            if (pa != pb)
            {
                d[pa] = sz[pb];
                sz[pb] += sz[pa];
                p[pa] = pb;
            }
        }
        else
        {
            int pa = find(a), pb = find(b);
            if (pa != pb) puts("-1");
            else printf("%d\n", max(0, abs(d[a] - d[b]) - 1));
        }
    }
    
    return 0;
}

参考资料

  1. AcWing算法提高课

你可能感兴趣的:(并查集,数据结构,算法,并查集)