08-图7 公路村村通(30 分)

08-图7 公路村村通(30 分)

现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。

输入格式:

输入数据包括城镇数目正整数N1000)和候选道路数目M3N);随后的M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号以及该道路改建的预算成本。为简单起见,城镇从1到N编号。

输出格式:

输出村村通需要的最低成本。如果输入数据不足以保证畅通,则输出1,表示需要建设更多公路。

输入样例:

6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3

输出样例:

12
作者: 陈越
单位: 浙江大学
时间限制: 400ms
内存限制: 64MB
代码长度限制: 16KB

#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
using namespace std;
struct Rode {
	int StartPoint;
	int EndPoint;
	int Cost;
	friend bool operator <(const Rode& r1, const Rode& r2)
	{
		return r2.Cost < r1.Cost;
	}
};
int FindRoot(int index, vector<int> & v)
{
	if (v[index] < 0) {
		return index;
	}
	else {
		return v[index] = FindRoot(v[index], v);
	}
}
void Union(int root1,int  root2, vector<int>& v)
{
	v[root1] = root2;
}
int main()
{
	//ifstream inFile("C:\\Users\\DELL\\Desktop\\in.txt");
	int N;//城镇数目;
	int M;//候选道路数目M(≤3N)
	cin >> N >> M;
	priority_queue<Rode, vector<Rode>> Q;
	vector<int> v(N + 1, -1);
	Rode R;
	for (int i = 0; i < M; ++i) {
		cin >> R.StartPoint >> R.EndPoint >> R.Cost;
		Q.push(R);
	}
	int count = 0, mincost = 0;
	while (count < N - 1 && Q.size()) {
		Rode r = Q.top();
		Q.pop();
		int root1 = FindRoot(r.StartPoint, v);
		int root2 = FindRoot(r.EndPoint, v);
		if (root1 != root2) {
			count++;
			mincost += r.Cost;
			Union(root1, root2, v);
		}
	}
	if (count < N-1) {
		cout << "-1" << endl;
	}
	else {
		cout << mincost << endl;
	}
//	inFile.close();
	system("pause");
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值