dijkstra算法:链式前向星+堆优化

Posted st-lovaer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了dijkstra算法:链式前向星+堆优化相关的知识,希望对你有一定的参考价值。

最近发现struct板子真的好用。

 1 #include<bits/stdc++.h>
 2 #define ll long long 
 3 #define scan(i) scanf("%d",&i)
 4 #define scand(i) scanf("%lf",&i)
 5 #define scanl(i) scanf("%lld",&i)
 6 #define f(i,a,b) for(int i=a;i<=b;i++) 
 7 #define pb(i) push_back(i)
 8 #define ppb pop_back()
 9 #define pf printf
10 #define input freopen("in.txt","r",stdin)
11 #define output freopen("out.txt","w",stdout)
12 #define io ios::sync_with_stdio(0)
13 #define dbg(args...) cout<<#args<<" : "<<args<<endl
14 #define inf 0x3f3f3f3f
15 #define pii pair<int, int>
16 const int mod = 1e9+7;
17 const int maxn = 2e5+7;
18 using namespace std;
19 struct node {int to,w,next;} edge[maxn];
20 int n,m;
21 struct Dijkstra{
22     int dis[maxn], vis[maxn];
23     int head[maxn],cnt;
24     int s,t;
25     
26     void init(){
27         memset(head,-1,sizeof(head));
28         memset(dis,0x3f,sizeof(dis));
29         memset(vis,0,sizeof(vis));
30         cnt = 0;
31     }
32  
33     void add(int u,int v,int w){
34         edge[cnt].to = v;
35         edge[cnt].w = w;
36         edge[cnt].next = head[u];
37         head[u] = cnt++;
38     }
39  
40     void dijkstra(){
41         priority_queue<pii,vector<pii>,greater<pii> > q;//从小到大
42         dis[s] = 0; q.push({dis[s],s});
43         while(!q.empty()){
44             int now = q.top().second;
45             q.pop();
46             if(vis[now]) continue;
47             vis[now] = 1;
48             for(int i = head[now]; i != -1; i = edge[i].next){
49                 int v = edge[i].to;
50                 if(dis[v] > dis[now] + edge[i].w){
51                     dis[v] = dis[now] + edge[i].w;
52                     q.push({dis[v],v});
53                 }
54             }
55         }
56     }
57 }dj;
58  
59 int main(){
60     while(~scanf("%d%d",&n,&m) && n+m){
61         dj.init();
62         for(int i = 0; i < m; i++){
63             int u, v, w;
64             scanf("%d%d%d",&u, &v, &w);
65             dj.add(u, v, w);
66             dj.add(v, u, w);
67         }
68         dj.s=1,dj.t=n;//s起点,t终点
69         dj.dijkstra();
70         printf("%d
",dj.dis[dj.t]);
71     }
72 }

 

以上是关于dijkstra算法:链式前向星+堆优化的主要内容,如果未能解决你的问题,请参考以下文章

dijkstra最短路算法(堆优化)

2/1 最短路径和链式前向星的结合应用

1163 Dijkstra Sequence + 层序遍历 + 链式前向星

AcWing 4246. 最短路径和(反向建图+链式前向星+堆优化)

Dijkstra

[poj3159]Candies(差分约束+链式前向星dijkstra模板)