spfa模板

 1 #include<iostream>
 2 #include<cmath>
 3 #include<algorithm>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<queue>
 7 #define inf 2147483647
 8 using namespace std;
 9 struct data
10 {
11     int from,to,next,w;
12     data(){from=-1,to=-1,next=-1,w=-1;}
13 }e[2000];
14 int n,m;
15 int head[2000];
16 int d[2000],p[2000],sum[2000];
17 bool vis[2000];
18 int cnt=0;
19 void add(int u,int v,int w){e[cnt].from=u,e[cnt].to=v;e[cnt].next=head[u],head[u]=cnt,e[cnt].w=w,cnt++;}
20 bool spfa(int s)
21 {
22     queue<int> q;
23     for(int i=1;i<=n;i++) d[i]=inf;
24     q.push(s);
25     d[s]=0;
26     memset(vis,0,sizeof(vis));
27     vis[s]=1;
28     while(!q.empty())
29     {
30         int x=q.front();
31         q.pop();
32         vis[x]=0;
33         for(int i=head[x];i>=0;i=e[i].next)
34         {
35             if(d[e[i].from]<inf&&d[e[i].to]>d[e[i].from]+e[i].w)
36             {
37                 d[e[i].to]=d[e[i].from]+e[i].w;
38                 p[e[i].to]=i;
39                 if(!vis[e[i].to]){q.push(e[i].to);vis[e[i].to]=1;if(++sum[e[i].to]>n) return false;}
40             }
41         }
42     }
43     return true;
44 }
45 int main()
46 {
47     memset(head,-1,sizeof(head));
48     scanf("%d%d",&n,&m);
49     for(int i=1;i<=m;i++)
50     {
51         int u,v,w;
52         scanf("%d%d%d",&u,&v,&w);
53         add(u,v,w);
54         add(v,u,w);
55     }
56     int s,t;
57     scanf("%d%d",&s,&t);
58     spfa(s);
59     cout<<d[t];
60 }
View Code

 

posted @ 2016-06-18 23:39  wls001  阅读(119)  评论(0编辑  收藏  举报