比赛 板子大赛 评测结果 AAAAAAAAAA
题目名称 通信线路 最终得分 100
用户昵称 喵喵喵 运行时间 0.060 s
代码语言 C++ 内存使用 3.41 MiB
提交时间 2025-01-22 09:20:27
显示代码纯文本
#include <bits/stdc++.h>
using namespace std;
int n;
const int N = 1510,M = 1e4 + 10;
struct Edge
{
	int x,y,w;
} e[M];
bool cmp(Edge &a,Edge &b)
{
	return a.w < b.w;
}
int f[N];
void init()
{
	for(int i = 1; i <= N; ++i) f[i] = i;
}
int get(int x)
{
	if(x == f[x]) return x;
	return f[x] = get(f[x]);
}
void merge(int x,int y)
{
	int fx = get(x),fy = get(y);
	if(fx != fy) f[fy] = fx;
}
void kruskal()
{
	init();
	int ans = 0;
	for(int i = 1;i <= M;i++)
	{
		int x = e[i].x,y = e[i].y,w = e[i].w;
		if(get(x) != get(y))
		{
			merge(x,y);
			ans += w;
		}
	}
	cout << ans << endl;
}
int main()
{
	freopen("mcst.in","r",stdin);
	freopen("mcst.out","w",stdout);
	cin >> n;
	int ind = 0;
	for(int i = 0;i < n;i++)
	{
		for(int j = 0;j < n;j++)
		{
			int op;
			cin >> op;
			if(op != -1) e[ind].x = i + 1,e[ind].y = j + 1,e[ind].w = op,ind++;
		}
	}
	sort(e,e+M,cmp);
	kruskal();
	return 0;
}