POJ 2387 Til the Cows Come Home (最短路径,Dijkstra算法)

拼搏现实的明天。 2024-02-18 16:42 105阅读 0赞

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

* Line 1: Two integers: T and N

* 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

* Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.

Sample Input

  1. 5 5
  2. 1 2 20
  3. 2 3 30
  4. 3 4 20
  5. 4 5 20
  6. 1 5 100

Sample Output

  1. 90

Hint

INPUT DETAILS:

There are five landmarks.

OUTPUT DETAILS:

Bessie can get home by following trails 4, 3, 2, and 1.

n^2算法:

AC代码:

  1. #include<cstdio>
  2. #include<algorithm>
  3. #include<cstring>
  4. using namespace std;
  5. const int maxn = 1e3+10;
  6. const int INF = 1e8;
  7. int d[maxn];
  8. int w[maxn][maxn];
  9. int vist[maxn];
  10. int main(){
  11. int T,N;
  12. while(scanf("%d%d",&T,&N)==2){
  13. memset(w,0,sizeof(w));
  14. for(int i = 1; i <= T; i++){
  15. int a,b,t;
  16. scanf("%d%d%d",&a,&b,&t);
  17. if(w[a][b] && w[a][b] < t) continue; //注意这里需要判断
  18. w[a][b] = w[b][a] = t;
  19. }
  20. for(int i = 1; i <= N; i++) i == 1 ? d[i] = 0 : d[i] = INF;
  21. memset(vist,0,sizeof(vist));
  22. for(int i = 1; i <= N; i++){
  23. int Min = INF,x;
  24. for(int j = 1; j <= N; j++)
  25. if(!vist[j] && d[j] <= Min)
  26. Min = d[x=j];
  27. vist[x] = 1;
  28. for(int y = 1; y <= N; y++)
  29. if(w[x][y])
  30. d[y] = min(d[y],d[x] + w[x][y]);
  31. }
  32. printf("%d\n",d[N]);
  33. }
  34. return 0;
  35. }

发表评论

表情:
评论列表 (有 0 条评论,105人围观)

还没有评论,来说两句吧...

相关阅读