跳到正文

个人记录

Make It Connected

__DragonFly约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年8月12日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 3 分钟

版本

  1. v1当前

题目思路

题目就是要我们求一个最小生成树,但是时间限制 2000ms2000ms, primprim 算法会超时,考虑使用克鲁斯卡尔算法。注意空间限制 262144kB262144 kB,如果正常连边会 MLEMLE,所以应当想一种存边方式使得空间不超限。因为这道题的边权求法特殊为 ai+aja_i+a_j ,所以 aia_i 越小,那么权值就越小,那我们可以求出点权最小的点 idid ,让所有的 aia_i 与 idid 连边,再求一遍克鲁斯卡尔,但优惠的边不改变。

正确思路

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 2e5 + 7, M = N * 2; // 因为第一遍建边最多为n-1条,另一个建边为m,n<=m<=2e5,所以为2*2e5
struct node {
	int u, v, val;
}e[M];
int a[N];
int fa[N], n, m, cnt, minn = 1e18, id;

void init() {
	for (int i = 1; i <= n; ++i) fa[i] = i;
	return ;
}

int find(int u) {
	if (fa[u] == u) return u;
	return fa[u] = find(fa[u]);
}

bool cmp(node q, node h) {
	return q.val < h.val;
}

signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	cin >> n >> m;
	init();
	for (int i = 1; i <= n; ++i) {
		cin >> a[i];
		if (a[i] < minn) {
			minn = a[i];
			id = i;
		}
	}
//	cout << id << "\n"; 
	for (int i = 1; i <= n; ++i) {
		cnt++;
		e[cnt].u = i;
		e[cnt].v = id;
		e[cnt].val = a[i] + a[id];
	}
	for (int i = 1; i <= m; ++i) {
		int x, y, w;
		cin >> x >> y >> w;
		cnt++;
		e[cnt].u = x;
		e[cnt].v = y;
		e[cnt].val = w;
	}
	sort(e + 1, e + 1 + cnt, cmp);
	int sum = 0;
	for (int i = 1; i <= cnt; ++i) {
		int t1 = find(e[i].u), t2 = find(e[i].v);
		if (t1 == t2) continue;
		sum += e[i].val;
		fa[t1] = t2;
	}
	cout << sum;
	return 0;
}
原文