MST模板:使用priority_queue实现的Prim算法

测试数据:

8 16
4 5 .35
4 7 .37
5 7 .28
0 7 .16
1 5 .32
0 4 .38
2 3 .17
1 7 .19
0 2 .26
1 2 .36
1 3 .29
2 7 .34
6 2 .40
3 6 .52
6 0 .58
6 4 .93

测试结果:

1.81


代码:

#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<utility>
#include<functional>
using namespace std;
const int mx = 10005;

typedef pair<double, int> P; ///first是当MST与该点连接时,所连的那条边的长度,second是顶点编号
struct edge
{
	double cost;
	int to;
	edge(double cost = 0.0, int to = 0): cost(cost), to(to) {}
} e;

vector<edge> G[mx];
double disTo[mx]; /// 当MST与点i连接时,所连的那条边的长度
bool vis[mx];
priority_queue<P, vector<P>, greater<P> > pq;

///复杂度:O(ElogV)
double prim()
{
	P p;
	int v, i;
	double sumcost = 0.0;
	memset(disTo, 100, sizeof(disTo));
	memset(vis, 0, sizeof(vis));
	disTo[0] = 0.0;
	while (!pq.empty()) pq.pop();
	pq.push(P(0.0, 0));/// 从点0开始构造MST
	while (!pq.empty())
	{
		p = pq.top(), pq.pop();
		v = p.second; /// v视作e.from
		if (vis[v] || p.first > disTo[v]) continue;
		vis[v] = true;
		sumcost += disTo[v];
		for (i = 0; i < G[v].size(); ++i)
		{
			e = G[v][i]; /// v视作e.from
			if (disTo[e.to] > e.cost)
			{
				disTo[e.to] = e.cost;
				pq.push(P(disTo[e.to], e.to));
			}
		}
	}
	return sumcost;
}

int main()
{
	int n, m, i, a, b;
	double cost;
	while (~scanf("%d%d", &n, &m))
	{
		for (i = 0; i < n; ++i) G[i].clear();
		while (m--)
		{
			scanf("%d%d%lf", &a, &b, &cost);
			G[a].push_back(edge(cost, b));
			G[b].push_back(edge(cost, a));
		}
		printf("%.2f\n", prim());
	}
	return 0;
}


O(V^2)复杂度的算法见

http://blog.csdn.net/synapse7/article/details/18141059

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值