标签:
http://acm.hdu.edu.cn/showproblem.php?pid=2544
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 41979 Accepted Submission(s): 18360
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 using namespace std; 5 #define N 250 6 #define M 10005 7 #define INF 0x1fffffff 8 struct Edge{ 9 int to; 10 int w ; 11 int next; 12 }edge[M]; 13 int Enct; 14 int head[N]; 15 void init() 16 { 17 Enct = 0; 18 memset(head,-1,sizeof(head)); 19 } 20 void add(int from , int to,int w) 21 { 22 edge[Enct].to= to; 23 edge[Enct].w = w; 24 edge[Enct].next = head[from]; 25 head[from] = Enct++; 26 edge[Enct].to= from; 27 edge[Enct].w = w; 28 edge[Enct].next = head[to]; 29 head[to] = Enct++; 30 } 31 int que[N]; 32 bool inq[N]; 33 int top; 34 int dis[N]; 35 int n; 36 int SPFA() 37 { 38 memset(inq,0,sizeof(inq)); 39 for(int i =0 ;i <= n ;i++) 40 dis[i] = INF; 41 top = 0; 42 dis[1] = 0; 43 que[top++] = 1; 44 inq[1]=true; 45 for(int i = 0;i != top ;i = i+1%N)//队列不为空,注意i和top不是同时循环到下一次的 46 { 47 int u = que[i]; 48 inq[u]=false; 49 for(int j = head[u] ; j!=-1 ;j = edge[j].next) 50 { 51 Edge e = edge[j]; 52 if(dis[e.to]>dis[u]+e.w) 53 { 54 dis[e.to] = dis[u]+e.w; 55 if(inq[e.to]==false) 56 { 57 que[top++] = e.to; 58 top %= N;//循环队列 59 inq[e.to] = true; 60 } 61 } 62 } 63 } 64 return dis[n]; 65 } 66 int main() 67 { 68 int m ; 69 while(~scanf("%d %d",&n,&m) && (n!=0||m!=0)) 70 { 71 init(); 72 int s , t , w; 73 for(int i = 0 ;i < m ;i++) 74 { 75 scanf("%d%d%d",&s,&t,&w); 76 add(s,t,w); 77 } 78 printf("%d\n",SPFA()); 79 } 80 return 0; 81 }
标签:
原文地址:http://www.cnblogs.com/shanyr/p/4707253.html