RT,谜之RE,算法可能是假的,但RE
  • 板块题目总版
  • 楼主goodbyeOI
  • 当前回复6
  • 已保存回复6
  • 发布时间2024/7/15 08:45
  • 上次更新2024/7/15 10:04:31
查看原帖
RT,谜之RE,算法可能是假的,但RE
1396294
goodbyeOI楼主2024/7/15 08:45

记录

#include <bits/stdc++.h>
using namespace std;
#define int long long 
const int N = 1e7 + 5;
int n, k, fa[N];
bool aim[N];
int tot = 1;
struct edge {
	int from, to, val;
} e[N] ;
int find (int x) {
	if (fa[x] == x) return x;
	return fa[x] = find(fa[x]);
}
bool cmp(edge a, edge b) {
	return a.val < b.val;
}
int kruscal() {
	int ans = 0, cnt = 1;
	sort(e + 1, e + 1 + tot, cmp);
	for (int i = 1; i <= tot; i++) {
		int f1 = find(e[i].from), f2 = find(e[i].to);
		if (f1 != f2 && (aim[f1] && aim[f2])) {
			fa[f2] = f1;
			ans += e[i].val;
			cnt++;
		}
		if (cnt == k) return ans;
	}
}

signed main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin >> n >> k;
	for (int i = 0; i < k; i++) {
		int x;
		cin >> x;
		aim[x] = 1;
	}
	for (int i = 1; i <= n + 5; i++) fa[i] = i;
	for (int i = 1; i <= n - 1; i++) {
		int a, b, c;
		cin >> a >> b >> c;
		e[++tot].from = a;
		e[tot].to = b;
		e[tot].val = c;
	}
	cout << kruscal();
	return 0;
}
2024/7/15 08:45
加载中...