堆优化的dijkstra算法

dijkstra算法是查找单源最短路径的算法,但它的时间复杂度过高,因此就有了空间换时间的方法,用堆来进行优化,这里只介绍priority_queue()的做法。
废话不多说,代码中讲

#include <iostream>
#include <queue>
#include <vector>
#include <cstring>

using namespace std;

const int INF = 0x3f3f3f3f;
const int maxn = 10000;
int n;

struct node
{
	int to, cost;
	
	node (int a, int b): to(a), cost(b) {}
	bool operator < (const node &b) const
	{
		return cost > b.cost;
	}
};

vector<node> G[maxn];
int vis[maxn], dis[maxn], pre[maxn];
//标记点有没有被访问过,记录源点到某点的最短距离,记录前驱/路径

void dijkstra(int start)
{
	priority_queue<node> que;
	memset(vis,.0, sizeof(vis));
	memset(dis, INF, sizeof(dis));
	memset(pre, INF, sizeof(pre));

	dis[start] = 0;
	que.push(node(start, 0));
	pre[start] = start;  //源点没有前驱
	
	while (!que.empty())
	{
		node front = que.top();
		int tempv = front.to;
		que.pop();
		
		if (vis[tempv])
		{
			continue;
		}
	
		vis[tempv] = 1;

		for (int i=0; i<G[tempv].size(); i++)
		{
			int p = G[tempv][i].to;
		
			if (!vis[p] && dis[tempv]+G[tempv][i].cost < dis[p])
			{
				dis[p] = dis[tempv] + G[tempv][i].cost;
				pre[p] = tempv;   //找前驱的
				que.push(node(p, dis[p]));
			}
		}
	}
}

void dth(int d)   //查找路径也就是前驱的函数
{
	if (d!=pre[d])
	{
		dth(pre[d]);
	}
	
	cout << d+1 << " ";
}

int main()
{
	int n, m, s;
	
	cin >> n >> m >> s;
	//n为顶点个数,m为边的条数,s为源点
	
	for (int i=0; i<m; i++)
	{
		int from, to, cost;

		cin >> from >> to >> cost;
	
		from--;    //顶点是从1开始的但是邻接表得从零开始,所以所有数据都减一
		to--;
		G[from].push_back(node(to, cost));
		G[to].push_back(node(from, cost));
	}

	dijkstra(s-1);

	for (int i=0; i<n; i++)
	{
		cout << dis[i] << " "; 
	}

	cout << endl;
	cout << dis[n-1] << endl;   //这里的n-1是任意的我只是为了方便才这么写的
	dth(n-1);
	
	return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值