Til the Cows Come Home

 1 Til the Cows Come Home
 2 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.
 3 
 4 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.
 5 
 6 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.
 7 Input
 8 * Line 1: Two integers: T and N
 9 
10 * 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.
11 Output
12 * Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.
13 Sample Input
14 5 5
15 1 2 20
16 2 3 30
17 3 4 20
18 4 5 20
19 1 5 100
20 Sample Output
21 90
22 Hint
23 INPUT DETAILS:
24 
25 There are five landmarks.
26 
27 OUTPUT DETAILS:
28 
29 Bessie can get home by following trails 4, 3, 2, and 1.

基础的求最短路径的问题,边权都为正,可以采用dijksra或者Floyd算法,在这里使用的第一种,在本题中就是要注意一下重边的情况,其实通过这个题就可以在基础的dijksra算法中每次都添加判断重边的情况。

代码:

 1 #include <iostream>
 2 #include<cstdio>
 3 #include <algorithm>
 4 using namespace std;
 5 int d[1010];
 6 int w[1010][1010] = {0};
 7 int v[1010] = {0};
 8 const int INF = 0x3f3f3f3f;
 9 int main()
10 {
11     int T, N;
12     cin >> T >> N;
13     int i;
14     for (i = 1; i <= N; i++)
15     {
16         if (i == 1)
17             d[i] = 0;
18         else
19             d[i] = INF;
20     }
21     int a, b, c;
22     int j;
23    for(i=1;i<=N;i++)
24    {
25        for(j=1;j<=N;j++)
26        w[i][j]=INF;
27    }
28     for (i = 1; i <= T; i++)
29     {
30         scanf("%d%d%d", &a, &b, &c);
31         w[a][b] = min(w[a][b], c);
32         w[b][a] = w[a][b];
33     }
34     for (i = 1; i <= N; i++)
35     {
36         int x, m = INF;
37         for (int y = 1; y <= N; y++)
38         {
39             if (!v[y] && d[y] <= m)
40             {
41                 x = y;
42                 m = d[x];
43             }
44         }
45         v[x] = 1;
46         for (int y = 1; y <= N; y++)
47         {
48             d[y] = min(d[y], d[x] + w[x][y]);
49         }
50     }
51     printf("%d\n", d[N]);
52     return 0;
53 }

这样就完成了。

posted @ 2021-01-20 12:09  IChase  阅读(41)  评论(0)    收藏  举报
Live2D