5-10 公路村村通 (30分)

#include <iostream>
#include <algorithm>

using namespace std;

struct edge
{
	int a, b, cost;
}e[3010];

int sum[1010], tree[1010], res;

int cmp(edge e1, edge e2)
{
	return e1.cost < e2.cost;
}

int findroot(int root)
{
	if(tree[root] == -1)
	{
		return root;
	}
	else
	{
		tree[root] = findroot(tree[root]);
		return tree[root];
	}
}

void buildrelation(edge e)
{
	int index[2];
	index[0] = e.a;
	index[1] = e.b;

	int i;
	for(i = 0; i < 2; i++)
	{
		index[i] = findroot(index[i]);
	}

	if(index[0] == index[1])
	{
		return;
	}

	int index0 = index[0], index1 = index[1];
	if(sum[index1] > sum[index0])
	{
		index[0] = index1;
		index[1] = index0;
	}

	tree[index1] = index0;
	sum[index0] += sum[index1];
	res += e.cost;
}

int getrootcount(int n)
{
	int i, count = 0;
	for(i = 1; i <= n; i++)
	{
		if(tree[i] == -1)
		{
			count++;
		}
	}

	return count;
}

int main()
{
	int n, m;
	scanf("%d%d", &n, &m);

	int i;
	for(i = 1; i <= m; i++)
	{
		scanf("%d%d%d", &e[i].a, &e[i].b, &e[i].cost);
	}

	sort(e + 1, e + m + 1, cmp);

	for(i = 1; i <= n; i++)
	{
		sum[i] = 1;
		tree[i] = -1;
	}

	for(i = 1; i <= m; i++)
	{
		buildrelation(e[i]);
	}

	if(getrootcount(n) > 1)
	{
		printf("-1\n");
		return 0;
	}

	printf("%d\n", res);

	system("pause");
	return 0;
}

 

posted on 2025-11-29 14:59  王景迁  阅读(0)  评论(0)    收藏  举报

导航