四川大学 数据结构实验课 最小二叉生成树

#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
typedef pair<char, char> pchar;
map<char, int> cindex;//记录每个点的编号
vector<vector<int>> matrix;//邻接矩阵
bool judge_tree( pchar pch,int size) {//利用求传递闭包算法,判断新边是否是matrix中的边的传递边,来验证是否构成了环。
	vector<vector<int>> temp = matrix;
	for (int i = 0; i < size; i++) {
		vector<int> line;
		for (int j = 0; j < size; j++) {
			line.push_back(temp[j][i]);
		}
		for (int k = 0; k < size; k++) {
			if (temp[i][k] == 1) {
				for (int m = 0; m < size; m++) {
					temp[m][k] += line[m];
				}
			}
		}
	}
	if (temp[cindex[pch.first]][cindex[pch.second]] > 0) return false;
	else return true;

}
static bool com(pair<pchar, int> a, pair<pchar, int> b) {
	return a.second < b.second;
}
int main() {
	map<pchar, int > Map;//记录边和其权重
	map<char, int> visited;//是否有踩过这个点
	int points_num, edge_num;
	cout << "input all the points" << endl;
	int index = 0;
	char ch='a';
	while (ch!='0') {
		cin >> ch;
	
		cindex[ch] = index++;
	}
	 int size = cindex.size();
	vector<int> temp(size, 0);
	for (int i = 0; i < size; i++)
		matrix.push_back(temp);
	cout << "input two points and the weight" << endl;
	char a, b;
	int weight;
	while (cin >> a >> b >> weight) {
		pchar pch(a, b);
		Map[pch] = weight;
	}
	vector<pair<pchar, int>> ve(Map.begin(), Map.end()), answer;/e:导入vector方便排序。answer:记录录入的边。
	sort(ve.begin(), ve.end(), com);
	answer.push_back(ve[0]);
	char point1 = ve[0].first.first;
	char point2 = ve[0].first.second;
	matrix[cindex[point1]][cindex[point2]] = 1;
	matrix[cindex[point2]][cindex[point1]] = 1;
	for (int i = 1; i < ve.size(); i++) {
		if (judge_tree(ve[i].first, size)) {
			answer.push_back(ve[i]);
			point1 = ve[i].first.first;
			point2 = ve[i].first.second;
			matrix[cindex[point1]][cindex[point2]] = 1;
			matrix[cindex[point2]][cindex[point1]] = 1;
		}
	}
	//output the result
	cout << "the answer is" << endl;
	for (int i = 0; i < answer.size(); i++) {
		cout << answer[i].first.first << " " << answer[i].first.second << " " << answer[i].second << endl;
	}
	return 0;
	
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值