最短路算法模板

本文最后更新于:3 years ago

1.Dijkstra(适合于稠密图)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n'
const ll inf=0x3f3f3f3f;
inline void FAST_IO() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
const int N=2e4+5;
int dist[N],vis[N],gap[N][N];
int n,m;
inline ll down(ll a,ll b){
return a<b?a:b;
}
void dijkstra(){
for(int i=1;i<=n;i++){
dist[i]=inf;
vis[i]=0;
}
dist[1]=0;
while(true){
int minNum=inf,ans=-1;
for(int i=1;i<=n;i++){
if(!vis[i]&&minNum>dist[i]){
minNum=dist[i];
ans=i;
}
}
if(ans==-1)break;
vis[ans]=1;
for(int i=1;i<=n;i++){
if(!vis[i]&&dist[i]>dist[ans]+gap[ans][i]){
dist[i]=dist[ans]+gap[ans][i];
}
}
}
cout<<dist[n]<<endl;
}
signed main() {
FAST_IO();
while(cin>>n>>m){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
gap[i][j]=(i==j?0:inf);
}
}
for(int i=0;i<m;i++){
int a,b,v;
cin>>a>>b>>v;
gap[a][b]=gap[b][a]=down(gap[a][b],v);
}
dijkstra();
}
return 0;
}

2.堆优化版本(适合解决稀疏图)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n'
const ll inf=0x3f3f3f3f;
inline void FAST_IO() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
const int MAXN=2e6;
const int N=1e4+5;
struct Edge{
int to,val,nxt;
}e[MAXN];
int head[N],dist[N],vis[N];
int n,m,tot;
inline void add(int from,int to,int val){
e[tot]=Edge{to,val,head[from]};
head[from]=tot++;
}
struct node{
int index,dist;
friend bool operator < (const node &a,const node &b){
return a.dist>b.dist;
}
};
void dijkstra(){
for(int i=1;i<=n;i++){
dist[i]=inf;
vis[i]=0;
}
dist[1]=0;
priority_queue<node>q;
q.push(node{1,0});
while(!q.empty()){
node now=q.top();
q.pop();
if(vis[now.index]==1)continue;
vis[now.index]=0;
for(int i=head[now.index];i!=-1;i=e[i].nxt){
int to=e[i].to;
int val=e[i].val;
if(dist[to]>dist[now.index]+val){
dist[to]=dist[now.index]+val;
q.push(node{to,dist[to]});
}
}
}
cout<<dist[n]<<endl;
}
signed main() {
FAST_IO();
while(cin>>n>>m){
memset(head,-1,sizeof(head));
tot=0;
for(int i=0;i<m;i++){
int a,b,v;
cin>>a>>b>>v;
add(a,b,v);
add(b,a,v);
}
dijkstra();
}
return 0;
}


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!