AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

AcWing 238. 银河英雄传说    原题链接    简单

作者: 作者的头像   123456789123123 ,  2024-11-30 14:21:07 ,  所有人可见 ,  阅读 2


1


1

边带权的并查集

使用d[a]额外记录从a到根节点的距离,se记录某个集合的大小

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int N = 30005;
int t;
int f[N], d[N], se[N];

int search(int a)
{
    if(a == f[a]) return a;
    int father = search(f[a]);
    d[a] += d[f[a]];
    return f[a] = father;
}

void merge(int a, int b)
{
    a = search(a);
    b = search(b);
    f[a] = b;
    //重复合并会使d和se偏大
    d[a] = se[b];
    se[b] += se[a];
}

int main()
{
    cin >> t;
    for(int i = 1; i <= N; i++) f[i] = i, se[i] = 1;
    while(t--)
    {
        char x;
        int a, b;
        cin >> x >> a >> b;
        if(x == 'M')
        {
            if(search(a) != search(b))
            merge(a, b);
        }
        else if(x == 'C')
        {
            int res = 0;
            if(search(a) != search(b)) res = -1;
            else res = abs(d[a] - d[b]);

            if(res > 0) res--;
            cout << res << endl;
        }

    }

    return 0;
}

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息