题意:单源最短路
解题思路:队列优化的 bellman-ford 算法!
解题代码:
1 // File Name: 2544_1.cpp 2 // Author: darkdream 3 // Created Time: 2014年04月04日 星期五 22时37分45秒 4 5 #include<vector> 6 #include<list> 7 #include<map> 8 #include<set> 9 #include<deque> 10 #include<stack> 11 #include<bitset> 12 #include<algorithm> 13 #include<functional> 14 #include<numeric> 15 #include<utility> 16 #include<sstream> 17 #include<iostream> 18 #include<iomanip> 19 #include<cstdio> 20 #include<cmath> 21 #include<cstdlib> 22 #include<cstring> 23 #include<ctime> 24 #include<climits> 25 #include<queue> 26 using namespace std; 27 28 struct node{ 29 int x, d ; 30 node() 31 {} 32 node(int p,int q) 33 { 34 x = p; 35 d = q; 36 } 37 }; 38 vector <node> edge[200]; 39 int n , m ; 40 int dis[200]; 41 queue <int> lis; 42 int bellman_ford(int s) 43 { 44 for(int i = 1;i <= n;i ++) dis[i] = 1 << 27; 45 dis[s] = 0 ; 46 lis.push(s); 47 while(!lis.empty()) 48 { 49 int k = lis.front(); 50 lis.pop(); 51 int n = edge[k].size(); 52 for(int i = 0 ;i < n ;i ++) 53 { 54 if(dis[edge[k][i].x] > dis[k] + edge[k][i].d) 55 { 56 dis[edge[k][i].x] = dis[k] + edge[k][i].d; 57 lis.push(edge[k][i].x); 58 } 59 } 60 } 61 return 1; 62 } 63 int main(){ 64 //freopen("/home/plac/problem/input.txt","r",stdin); 65 //freopen("/home/plac/problem/output.txt","w",stdout); 66 while(scanf("%d %d",&n,&m)!= EOF) 67 { 68 if(n == 0 && m == 0 ) 69 break; 70 for(int i =1 ;i <= n;i++) 71 edge[i].clear(); 72 for(int i = 1;i <= m ;i ++) 73 { 74 int a, b, c; 75 scanf("%d %d %d",&a,&b,&c); 76 edge[a].push_back(node(b,c)); 77 edge[b].push_back(node(a,c)); 78 } 79 if(bellman_ford(1)) 80 printf("%d ",dis[n]); 81 } 82 return 0; 83 }