算法导论-第23章-最小生成树:Prime算法(基于vector)的C++实现

#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;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值