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

2021-02-18 09:17

阅读:379

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

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

 1 #include 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 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...) cout14 #define inf 0x3f3f3f3f
15 #define pii pair16 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,greater > 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 ){
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


评论


亲,登录后才可以留言!