采蜜 码蹄集

题目来源:码蹄集

题目描述:

在这里插入图片描述
在这里插入图片描述

Python代码实现:

MAXN = 100005

def get(x, fa):
    if x == fa[x]:
        return x
    fa[x] = get(fa[x], fa)
    return fa[x]

n, m = map(int, input().split())
a = [0]*(n+1)
fa = [i for i in range(n+1)]

a[1:] = map(int, input().split())

while m > 0:
    f, *args = map(int, input().split())
    if f == 1:
        x, y = args
        fx, fy = get(x, fa), get(y, fa)
        if fx != fy:
            fa[fy] = fx
            a[fx] += a[fy]
    else:
        x = args[0]
        print(a[get(x, fa)])
    m -= 1

Java代码实现:

import java.util.*;

class Main {
    static final int MAXN = 100005;
    static int[] a = new int[MAXN];
    static int[] fa = new int[MAXN];

    static int get(int x) {
        if (x == fa[x])
            return x;
        fa[x] = get(fa[x]);
        return fa[x];
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();

        for (int i = 1; i <= n; i++) {
            a[i] = scanner.nextInt();
            fa[i] = i;
        }

        while (m-- > 0) {
            int f = scanner.nextInt();
            if (f == 1) {
                int x = scanner.nextInt();
                int y = scanner.nextInt();
                int fx = get(x);
                int fy = get(y);
                if (fx != fy) {
                    fa[fy] = fx;
                    a[fx] += a[fy];
                }
            } else {
                int x = scanner.nextInt();
                System.out.println(a[get(x)]);
            }
        }
    }
}

C++代码实现:

参考链接:https://yxsmarter.blog.csdn.net/article/details/128211350?spm=1001.2014.3001.5502

#include <cstdio>
#define maxn 100005
using namespace std;

int n, m, a[maxn], fa[maxn];

inline int get(int x) {
    if (x == fa[x]) return x;
    return fa[x] = get(fa[x]);
}

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++) {
        scanf("%d", &a[i]);
        fa[i] = i;
    }
    while (m--) {
        int f = 0;
        scanf("%d", &f);
        if (f == 1) {
            int x, y;
            scanf("%d%d", &x, &y);
            int fx = get(x), fy = get(y);
            if (fx != fy) {
                fa[fy] = fx;
                a[fx] += a[fy];
            }
        } else {
            int x;
            scanf("%d", &x);
            printf("%d\n", a[get(x)]);
        }
    }
    return 0;
}

代码提交测试结果:

在这里插入图片描述
附B站老师讲解链接:https://www.bilibili.com/video/BV1cs4y137za/?t=311.9

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Magneto_万磁王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值