最小生成树问题 Kruskal算法 HDU-1863畅通工程

先来看看题目

Problem Description
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
Output
对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。

Sample Input
3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
0 100

Sample Output
3

本题运用Kruskal算法,并适用并查集数据结构,来判断加入的边是否会形成回路。

每次都选择权值最小的那个边,并判断改变两个端点是否在同一个集合中,如果不在在那就选择这个边作为最小生成树的边,反复此步骤直到所有顶点都加入了树,也就是生成树(也叫支撑树)。

#include<iostream>
#include<unordered_map>
#include<vector>
#include<queue>

using namespace std;

class road {
public:
	road(int a, int b, int c) :id(make_pair(a, b)), cost(c) {}
	friend bool operator > (const road& rhs1,const road& rhs2) {        // 重载小于符号,以适用优先队列,优先队列中是小顶堆
		return rhs1.cost > rhs2.cost;
	}
	pair<int, int> getStation() {
		return id;
	}
	int getCost() {
		return cost;
	}
private:
	pair<int, int> id;
	int cost;
};

// 并查集
class UnionFindSet {
public:
	UnionFindSet(const vector<int>& data) {
		for (int i = 0; i < data.size(); i++) {
			father[data[i]] = data[i];
			size[data[i]] = 1;
		}
	}

	int findRep(int a) {
		if (father[a] == a) return a;
		int rep = findRep(father[a]);
		father[a] = rep;
		return rep;
	}

	bool isSameRep(int a, int b) {
		return findRep(a) == findRep(b);
	}

	void Union(int a, int b) {
		int aRep = findRep(a);
		int bRep = findRep(b);
		if (aRep != bRep) {
			if (size[aRep] <= size[bRep]) {
				father[aRep] = bRep;
				size[bRep] += size[aRep];
			}
			else {
				father[bRep] = aRep;
				size[aRep] += size[bRep];
			}
		}
	}

	bool isConnected(int m) {         // 用于算法最后检测是否全部连通了,或者是否是一颗支撑树
		if (size[findRep(m)] == m) return true;
		else return false;
	}
private:
	unordered_map<int, int> father;
	unordered_map<int, int> size;
};
// 最小生成树问题
int main() {
	int n, m, i, j;
	while (true) {
		int result = 0;
		priority_queue<road, vector<road>, greater<road>> roads;
		scanf("%d%d", &n, &m);        //道路条数n、村庄数目m
		if (n == 0) break;
		vector<int> label(m, 0);
		
		for (i = 0; i < n; i++) {
			int a, b, c;
			scanf("%d%d%d", &a, &b, &c);
			road add(a, b, c);
			roads.push(add);
		}
		for (i = 0; i < m; i++) {
			label[i] = i+1;
		}
		UnionFindSet ufs(label);
		//贪心算法(Kruskal算法)
		while (!roads.empty()) {
			road top = roads.top();
			roads.pop();
			pair<int, int> id = top.getStation();
			int a = id.first, b = id.second;
			if (!ufs.isSameRep(a, b)) {
				ufs.Union(a, b);
				result += top.getCost();
			}
		}
		if (ufs.isConnected(m)) cout << result << endl;
		else cout << "?" << endl;
	}

	return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值