最短路迪杰斯特拉板子

这个算法是找单源最短路,思想就是找当前离起点最短的一条边去维护其余点的最短距离。
简单描述就是 a 能到b, b能到c, a能到c。那么对于a到c, 如果a到b再从b到c比a直接到c更短,那么就选则a-b-c,而不是直接选择a-c
算法就是不断找最小,然后维护。
模板:
邻接矩阵版本

#include<bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
const int inf = 0x3f3f3f3f;

int G[N][N];
int dist[N]; int vis[N]; //存储到起点的距离和是否访问

int n, m, s;

void Dij(int t){
	for(int i = 1; i <= n; i++) dist[i] = G[t][i], vis[i] = 0;
	dist[t] = 0;
	for(int i = 1; i <= n; i++){
		int Mn = inf, point = -1; //找最小
		for(int j = 1; j <= n; j++){
			if(!vis[j] && dist[j] < Mn){
				Mn = dist[j]; point = j;  
			}
		}
		if(point == -1) return ;
		vis[point] = 1;
		for(int j = 1; j <= n; j++){ //更新
			if(G[point][j] + Mn < dist[j] ){
				dist[j] = G[point][j] + Mn;
			}
		}
	}
}


int main(){
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	memset(G, 0x3f, sizeof(G));
	cin >> n >> m >> s;
	for(int i = 1, u, v, w; i <= m; i++){
		cin >> u >> v >> w;
		G[u][v] = min(G[u][v], w);//无向图要加上G[v][u]
	}
	Dij(s);
	for(int i = 1; i <= n; i++){
		cout << dist[i] << " ";
	}
}

堆优化版本,主要是优化了找最小的过程。
最好的地方是存图技巧。
学习之前要看链式前向星的方法,差不多就是把上面的代码翻译成堆优化版本。


#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 1e7 + 10;
#define int long long

ll dist[N];
bool vis[N];
struct vv{
	int to, w, next;
}G[N];
int head[N], cnt;
int n, m, s;
inline void add(int from, int to, int w){
	G[++cnt].w = w;
	G[cnt].to = to;
	G[cnt].next	= head[from]; 
	head[from] = cnt;	
}

struct bb{
	int dist, id;
	bool operator < (const bb f) const{
        return f.dist < dist;
	}
};

priority_queue<bb> q;

void Dij(int s){
	for(int i = 1; i <= n; i++) dist[i] = 2147483647;
	dist[s] = 0;
	q.push({0, s});
	while(!q.empty()){
		bb now = q.top();
		q.pop();
		if(vis[now.id]) continue;
		vis[now.id] = 1;
		for(int e = head[now.id]; e != 0; e = G[e].next){
			int to = G[e].to;
			dist[to] = min(dist[to], dist[now.id]+G[e].w);
			if(!vis[to]) q.push({dist[to], to});
		}
	}
}

signed main(){
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	
	cin >> n >> m >> s;
	for(int i = 1, u, v, w; i <= m; i++){
		cin >> u >> v >> w;
		add(u, v, w);
	}
	Dij(s);
	for(int i = 1; i <= n; i++) cout << dist[i] << ' ';
	cout << endl;
	
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值