洛谷 P3371 【模板】单源最短路径(弱化版)(dijkstra邻接链表)

题目传送门

解题思路:

传送门

AC代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 
 5 using namespace std;
 6 
 7 struct kkk {
 8     int from,to,v,next;
 9 }e[500001];
10 int n,m,s,head[500001],q,w,p,tot,ans[500001];
11 bool vis[500001];
12 
13 void add(int q,int w,int p) {
14     e[++tot].from = q;
15     e[tot].to = w;
16     e[tot].v = p;
17     e[tot].next = head[q];
18     head[q] = tot;
19 }
20 
21 void dijkstra(int s) {
22     memset(vis,0,sizeof(vis));
23     ans[s] = 0;
24     for(int i = 1;i <= n; i++) {
25         int id = 0,sum = 0x3f3f;
26         for(int j = 1;j <= n; j++)
27             if(!vis[j] && sum >= ans[j])
28                 sum = ans[j],id = j;
29         vis[id] = 1;
30         for(int j = head[id];j;j = e[j].next)
31             ans[e[j].to] = min(ans[e[j].to],ans[id] + e[j].v);
32     }
33 }
34 
35 int main() {
36     scanf("%d%d%d",&n,&m,&s);
37     for(int i = 1;i <= n; i++) 
38         ans[i] = 0x3f3f3f3f;
39     for(int i = 1;i <= m; i++) {
40         scanf("%d%d%d",&q,&w,&p);
41         add(q,w,p);
42         
43     }
44     dijkstra(s);
45     for(int i = 1;i <= n; i++) {
46         if(ans[i] == 0x3f3f3f3f) printf("2147483647 ");
47         else
48             printf("%d ",ans[i]);
49     }
50     return 0;
51 }

 

posted @ 2019-07-27 22:52  Mr^Simon  阅读(197)  评论(0编辑  收藏  举报