这个算法是找单源最短路,思想就是找当前离起点最短的一条边去维护其余点的最短距离。
简单描述就是 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;
}