银河英雄传说(并查集)(附C语言实现)

并查集不解释…… 

#include <stdio.h>
#include <memory.h>
#include <math.h>

int T;
int *father;
int *children;

int find_father(int x) {
    while (father[x] != -1) x = father[x];
    return x;
}  //找到根节点

int find_children(int x) {
    while (children[x] != -1) x = children[x];
    return x;
}  //找到子节点

int hb(int x, int y)  //y放到x的尾端
{
    int cx = find_children(x), fy = find_father(y);
    father[fy] = cx;
    children[cx] = fy;
}

int ask(int x, int y) {
    int fx = find_father(x);
    int fy = find_father(y);
    if (fx != fy)
        return -1;
    else {
        int k1 = 0;
        int k2 = 0;
        while (father[x] != -1) {
            x = father[x];
            k1++;
        }
        while (father[y] != -1) {
            y = father[y];
            k2++;
        }
        return int(fabs(k1 - k2)) - 1;
    }
}

int main() {
    freopen("Problem6.in", "r", stdin);
    freopen("Problem6.out", "w", stdout);
    scanf("%d/n", &T);
    char c;
    int x, y;
    father = new int[T + 1];
    children = new int[T + 1];
    memset(father + 1, -1, sizeof(int) * T);
    memset(children + 1, -1, sizeof(int) * T);
    int p = 0;
    for (int i = 1; i <= T; i++) {
        scanf("%c %d %d/n", &c, &x, &y);
        if (c == 'M') {
            hb(x, y);
            p++;
        }
        if (c == 'C') {
            printf("%d/n", ask(x, y));
            p++;
        }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值