题目来源:码蹄集
题目描述:
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