Dijkstra算法——单源最短路

Dijkstra是非常高效又稳定的算法

类似于从起点向周围广搜

存储:

  1. 将i节点所有的边用 动态数组e[i] 存储,
  2. bool done [i]  记录第i个节点是否已经找到最短路径
  3. 在集合中找到最近的点,用堆实现

 

步骤:

  1. 遍历所有i 所有的边,取最短路
  2. 把i 能到达的顶点放入堆中
  3. 更新dis 数组

b站上这个动图讲的很好:

https://www.bilibili.com/video/av54668527?from=search&seid=16217010812807332775

 

#include<bits/stdc++.h> 
using namespace std;
using lon = long long;

const int inf = 0x3f3f3f3f;
const int N = 1e6;
struct edge//用于存储图 
{
	int from, to, w;//起点, 终点, 权值 
	edge(int a, int b, int c)
	{from = a, to = b, w = c;}
}; 
struct node
{
	int id, dis;//节点,起点到节点的距离 
	node(int a, int b)
	{id = a; dis = b;}
	
	bool operator < (const node & t) const
	{
		return dis > t.dis;
	}
};
vector<edge> e[N];
priority_queue<node> Q;
int n, m, pre[N], end;
int dis[N];
bool done[N];

void dijkstra()
{
	for(int i = 0; i <= n; i++)//初始化 
	dis[i] = inf, done[i] = false;
	while(!Q.empty()) Q.pop(); 
	
	int s = 1;  dis[s] = 0;//起点是1,到自己的距离为0 
	Q.push(node(s,dis[s]));
	
	while(!Q.empty())
	{
		node u = Q.top(); Q.pop(); 
		
		if(done[u.id]) continue;//如果这个点已经找到最小距离 
		done[u.id] = true;//堆顶是最小距离,其他的都会pop出去 
		
		for(int i = 0; i < e[u.id].size(); i++)//找到这个定点所有的边 
		{
			edge y = e[u.id][i];
			if(done[y.to]) continue;
			
			if(dis[y.to] > u.dis + y.w) //比较 s-> to 和 s -> u -> to 
			{
				dis[y.to] = y.w + u.dis;
				Q.push(node(y.to, dis[y.to]));//将to放入堆, 会自动取最近的 
				pre[y.to] = u.id;
			}
		}
		
	}
	
	for(int i = end; i != 0; i = pre[i]) cout << i << ' ';//路径 
}

int main()
{
	while(cin >> n >> m)
	{
		for(int i = 0; i <= n; i++) e[i].clear();
		end = 6; //终点 
		while(m--)
		{
			int a, b, c;
			cin >> a >> b >> c;
			e[a].push_back(edge(a, b, c));
			e[b].push_back(edge(b, a, c));
		}
		
		dijkstra();
		
		cout << dis[end] << endl;
	}
	
	return 0;
}



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值