转自:http://www.wutianqi.com/?p=1894
畅通工程续
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 13049 Accepted Submission(s): 4436
code:
1 #include <iostream> 2 #include <iomanip> 3 #include <fstream> 4 #include <sstream> 5 #include <algorithm> 6 #include <string> 7 #include <set> 8 #include <utility> 9 #include <queue> 10 #include <stack> 11 #include <list> 12 #include <vector> 13 #include <cstdio> 14 #include <cstdlib> 15 #include <cstring> 16 #include <cmath> 17 #include <ctime> 18 #include <ctype.h> 19 using namespace std; 20 21 #define MAXN 201 22 23 int dis[MAXN]; 24 int pre[MAXN]; 25 int map[MAXN][MAXN]; 26 bool vst[MAXN]; 27 int n,m; 28 int s,t; 29 30 void Dijkstra() 31 { 32 int i,j; 33 for(i=1;i<=n;++i) 34 { 35 dis[i]=map[s][i]; 36 vst[i]=0; 37 } 38 dis[s]=0; 39 vst[s]=1; 40 for(i=2;i<=n;++i) 41 { 42 int mindis=INT_MAX; 43 int nextgoal=s; 44 for(j=1;j<=n;++j) 45 if((!vst[j])&&dis[j]<mindis) 46 { 47 nextgoal=j; 48 mindis=dis[j]; 49 } 50 vst[nextgoal]=1; 51 for(j=1;j<=n;++j) 52 if((!vst[j])&&(map[nextgoal][j]<INT_MAX)) 53 { 54 int updatedis=dis[nextgoal]+map[nextgoal][j]; 55 if(dis[j]>updatedis) 56 dis[j]=updatedis; 57 } 58 } 59 } 60 int main() 61 { 62 int i,j; 63 int a,b,distance; 64 while(~scanf("%d%d",&n,&m)) 65 { 66 for(i=1;i<=n;++i) 67 for(j=1;j<=n;++j) 68 { 69 if(i==j) 70 map[i][j]=0; 71 else 72 map[i][j]=INT_MAX; 73 } 74 for(i=1;i<=m;++i) 75 { 76 scanf("%d%d%d",&a,&b,&distance); 77 if(map[a+1][b+1]>distance) 78 { 79 map[a+1][b+1]=distance; 80 map[b+1][a+1]=distance; 81 } 82 } 83 scanf("%d%d",&s,&t); 84 s++; 85 for(i=1;i<=n;++i) 86 dis[i]=INT_MAX; 87 Dijkstra(); 88 if(dis[t+1]!=INT_MAX) 89 printf("%d\n",dis[t+1]); 90 else 91 printf("-1\n"); 92 } 93 return 0; 94 }