码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-04-13 18:19:39      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:mod   struct   oid   ace   NPU   pop   jks   ini   freopen   

最近发现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\n",dj.dis[dj.t]);
71     }
72 }

 

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

标签:mod   struct   oid   ace   NPU   pop   jks   ini   freopen   

原文地址:https://www.cnblogs.com/St-Lovaer/p/12692885.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!