Til the Cows Come Home
Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible.
Farmer John's field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it.
Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.Input
* Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.
Output
Sample Input
5 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100
Sample Output
90
挑战书上的写法,变通一下~~~~~
仔细读题very important!
1 #include<cstdio> 2 #include<iostream> 3 #include<string> 4 #include<algorithm> 5 using namespace std; 6 7 static const int MAX=1005; 8 static const int INFTY=(1<<21); 9 static const int WHITE=0; 10 static const int GRAY=1; 11 static const int BLACK=2; 12 13 int n,T,M[MAX][MAX]; 14 int Dijkstra() 15 { int minv; 16 int d[MAX],color[MAX]; 17 for(int i=1;i<=n;i++) 18 { d[i]=INFTY; 19 color[i]=WHITE; 20 } 21 d[1]=0; 22 color[1]=GRAY; 23 while(1) 24 { minv=INFTY; 25 int u=-1; 26 for(int i=1;i<=n;i++) 27 { if(minv>d[i]&&color[i]!=BLACK) 28 { u=i; 29 minv=d[i]; 30 } 31 } 32 if(u==-1) break; 33 color[u]=BLACK; 34 for(int v=1;v<=n;v++) 35 { if(color[v]!=BLACK&&M[u][v]!=INFTY) 36 { if(d[v]>d[u]+M[u][v]) 37 { d[v]=d[u]+M[u][v]; 38 color[v]=GRAY; 39 } 40 } 41 } 42 } 43 return d[n]; 44 } 45 int main() 46 { cin>>T>>n; 47 for(int i=1;i<=n;i++) 48 { 49 for(int j=1;j<=n;j++) 50 { M[i][j]=INFTY; 51 M[j][i]=INFTY; 52 } 53 } 54 int x,y,v; 55 for(int k=0;k<T;k++) 56 { scanf("%d%d%d",&x,&y,&v); 57 if(v<M[x][y]) //可能有多条路,选最短的路!!!! 58 { M[x][y]=v; 59 M[y][x]=v; //加双向边!!! 60 } 61 } 62 int ans=Dijkstra(); 63 cout<<ans<<endl; 64 65 return 0; 66 }

浙公网安备 33010602011771号