[模板][HDU]P2544[单源最短路][SPFA]

题目就不放了,主要是写一下SPFA,很少写,今天特别学了一个用STL的队列来做的。

代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<queue>
 5 using namespace std;
 6 inline int read();
 7 namespace lys{
 8     const int N = 1e2 + 7 ;
 9     const int M = 1e4 + 7 ;
10     struct edge{
11         int to;
12         int next;
13         int w;
14     }e[M*3];
15     int n,m,cnt;
16     int pre[N],dis[N];
17     bool exist[N];
18     void add(int x,int y,int w){
19         e[++cnt].to=y;e[cnt].next=pre[x];pre[x]=cnt;e[cnt].w=w;
20         e[++cnt].to=x;e[cnt].next=pre[y];pre[y]=cnt;e[cnt].w=w;
21     }
22     int spfa(){
23         memset(dis,127,sizeof dis);
24         dis[1]=0;
25         queue <int> q;
26         q.push(1),exist[1]=true ;
27         int x,i,v;
28         while(!q.empty()){
29             x=q.front(),q.pop();
30             exist[x]=false ;
31             for(i=pre[x];i;i=e[i].next){
32                 v=e[i].to;
33                 if(dis[x]+e[i].w<dis[v]){
34                     dis[v]=dis[x]+e[i].w;
35                     if(!exist[v]) q.push(v);
36                 }
37             }
38         }
39         return dis[n];
40     }
41     int main(){
42         int x,y,w;
43         while(true){
44             n=read(); m=read();
45             if(n==0) return 0;
46             memset(pre,0,sizeof pre);
47             cnt=0;
48             while(m--){
49                 x=read(); y=read(); w=read();
50                 add(x,y,w);
51             }
52             printf("%d\n",spfa());
53         }
54         return 0;
55     }
56 }
57 int main(){
58     lys::main();
59     return 0;
60 }
61 inline int read(){
62     int kk=0,ff=1;
63     char c=getchar();
64     while(c<'0'||c>'9'){
65         if(c=='-') ff=-1;
66         c=getchar();
67     }
68     while(c>='0'&&c<='9') kk=kk*10+c-'0',c=getchar();
69     return kk*ff;
70 }
posted @ 2017-11-08 19:10  iNx  阅读(186)  评论(0编辑  收藏  举报