#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
using namespace std;
static char elements_index{ 'a' };
using P = pair<char, int>;
struct Vertex {
char index{ elements_index++ };
int key{ numeric_limits<int>::max() };
bool in_queue{ true };
Vertex* parent{ nullptr };
};
void MST_PRIM(int* G, Vertex* V, vector<P>& v, char root, size_t n) {
V[root - 'a'].key = 0;
for (auto& a : v) {
if (a.first == root) {
a.second = 0;
}
}
char u{};
while (!v.empty()) {
sort(v.begin(), v.end(), [](const P& x, const P& y){ return x.second > y.second; });
u = v.back().first;
v.pop_back();
V[u - 'a'].in_queue = false;
for (int i = 0; i < n; ++i) {
if (G[(u - 'a') * n + i] != 0) {
if (V[i].in_queue && G[(u - 'a') * n + i] < V[i].key) {
V[i].parent = &V[u - 'a'];
V[i].key = G[(u - 'a') * n + i];
for (auto& a : v) {
if (a.first == V[i].index) {
a.second = V[i].key;
}
}
}
}
}
}
}
int main(int argc, char* argv[]) {
size_t vertex_size{};
cout << "please input the numbers of vertex :" << endl;
cin >> vertex_size;
Vertex* V = new Vertex[vertex_size]{};
vector<P> v{};
for (int i = 0; i < vertex_size; ++i) {
v.push_back({V[i].index, V[i].key});
}
int* G = new int[vertex_size * vertex_size]{};
char v0{};
char v1{};
int weight{};
cout << "please input the edge as : v0 v1 weight( end up with 0 0 0 )" << endl;
while (true) {
cout << "edge :" << endl;
cin >> v0 >> v1 >> weight;
if (v0 == '0' || v1 == '0' || weight == 0) {
break;
}
G[(v0 - 'a') * vertex_size + (v1 - 'a')] = G[(v1 - 'a') * vertex_size + (v0 - 'a')] = weight;
}
char root{};
cout << "please choose the root you want to built the MST :" << endl;
cin >> root;
MST_PRIM(G, V, v, root, vertex_size);
cout << "the result is :( @ presents there is no parent)" << endl;
for (int i = 0; i < vertex_size; ++i) {
cout << V[i].index << " parent :" << ((V[i].parent) ? V[i].parent->index : '@') << endl;
}
delete[]G;
delete[]V;
return 0;
}
算法导论-第23章-最小生成树:Prime算法(基于vector)的C++实现
最新推荐文章于 2021-12-20 23:16:38 发布