Help
查看原帖
Help
681272
Green_Yeast_King楼主2023/7/25 11:31

Sorry, This computer can't enter Chinese.

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 2e6 + 1;
int n, m, fa[N];
int x[N], y[N];
int ans = LONG_LONG_MAX;
int tot;
struct node {
	int a, b, v;
} f[N];
bool cmp (node a, node b) {
	return a.v < b.v;
}
int find (int x) {
	if (x != fa[x])
		fa[x] = find (fa[x]);
	return fa[x];
}
int kruscal () {
	sort (f + 1, f + 1 + tot, cmp);
	for (int i = 1; i <= n + 2; i ++ )
		fa[i] = i;
	int res = 0, cnt = 0;
	for (int i = 1; i <= tot; i ++ ) {
		int a = find (f[i].a), b = find (f[i].b);
		if (a != b) {
			fa[a] = b;
			res += f[i].v;
			cnt ++;
		} 
	}
	if (cnt < n - 1) return LONG_LONG_MAX;
	else return res;
}
main () {
	cin >> n >> m;
	for (int i = 1; i <= n; i ++ )
		cin >> x[i];
	for (int i = 1; i <= n; i ++ )
		cin >> y[i];
	for (int i = 1, a, b, v; i <= m; i ++ ) {
		cin >> a >> b >> v;
		f[++tot] = {a, b, v};
		f[++tot] = {b, a, v};
	}
	ans = min (ans, kruscal ());
	for (int i = 1; i <= n; i ++ ) {
		f[++tot] = {i, n + 1, x[i]};
		f[++tot] = {n + 1, i, x[i]};
	}
	ans = min (ans, kruscal ());
	tot = m;
	for (int i = 1; i <= n; i ++ ) {
		f[++tot] = {i, n + 2, y[i]};
		f[++tot] = {n + 2, i, y[i]};
	}
	ans = min (ans, kruscal ());
	for (int i = 1; i <= n; i ++ ) {
		f[++tot] = {i, n + 1, x[i]};
		f[++tot] = {n + 1, i, x[i]};
	}
	ans = min (ans, kruscal ());
	cout << ans << '\n';
	return 0;
}
2023/7/25 11:31
加载中...