spfa模板(洛谷3371)

洛谷P3371

 1 //spfa:求s到各点的最短路,可含负权边
 2 #include <cstdio>
 3 
 4 using namespace std;
 5 
 6 const int max_n=10010,max_m=500050,inf=2147483647;
 7 
 8 struct etype
 9 {
10     int t,w,next;
11 };
12 
13 etype e[max_m];
14 int a[max_n],dis[max_n],q[max_n+5],cnt;
15 int inq[max_n];
16 
17 void add(int u,int v,int w)
18 {
19     cnt++;e[cnt].t=v;e[cnt].w=w;
20     e[cnt].next=a[u];a[u]=cnt;
21 }
22 
23 int main()
24 {
25     int n,m,s;
26     scanf("%d%d%d",&n,&m,&s);
27     cnt=0;
28     for (int i=1;i<=m;i++)
29     {
30         int f,g,w;
31         scanf("%d%d%d",&f,&g,&w);
32         add(f,g,w);
33     }
34     for (int i=1;i<=n;i++)
35     {
36         inq[i]=false;
37         dis[i]=inf;
38     }
39     int h=0,t=1;
40     q[1]=s;dis[s]=0;inq[s]=true;
41     while (h!=t)
42     {
43         h++;if (h>max_n) h=1;
44         int i=a[q[h]];
45         while (i>0)
46         {
47             if (dis[q[h]]+e[i].w<dis[e[i].t])
48             {
49                 dis[e[i].t]=dis[q[h]]+e[i].w;
50                 if (!inq[e[i].t])
51                 {
52                     t++;if (t>max_n) t=1;
53                     q[t]=e[i].t;inq[e[i].t]=true;
54                 }
55             }
56             i=e[i].next;
57         }
58         inq[q[h]]=false;;
59     }
60     printf("%d",dis[1]);
61     for (int i=2;i<=n;i++) printf(" %d",dis[i]);
62     return 0;
63 }
原文地址:https://www.cnblogs.com/Currier/p/11288158.html