#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;
}
四川大学 数据结构实验课 最小二叉生成树
最新推荐文章于 2021-12-22 10:54:24 发布