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. The first line contains two integers t and n. Each line from 2 to t + 1 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. Print the minimum distance that Bessie must travel to get
from landmark n to landmark 1.
Sample input |
Sample output |
5 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100 |
90 |
ãðàôû - Äåéêñòðà
Àíàëèç àëãîðèòìà
Ïðè ïîìîùè àëãîðèòìà Äåéêñòðû èùåì
êðàò÷àéøèé ïóòü ìåæäó âåðøèíàìè 1 è n.
Ðåàëèçàöèÿ àëãîðèòìà
#include <cstdio>
#include <cstring>
#include <vector>
#define MAX
5010
#define INF
0x3F3F3F3F
using namespace std;
int i, t,
n, b, e, w;
int
used[MAX], dist[MAX];
vector<vector<pair<int, int> >
> g;
void
Relax(int v, int
to, int cost)
{
if (dist[to]
> dist[v] + cost)
dist[to] = dist[v] + cost;
}
int
Find_Min(void)
{
int i, v, min
= INF;
for(i = 1; i
<= n; i++)
if
(!used[i] && (dist[i] < min)) min = dist[i], v = i;
if (min ==
INF) return -1;
return v;
}
void
Dijkstra(void)
{
memset(used,0,sizeof(used));
memset(dist,0x3F,sizeof(dist));
dist[1] = 0;
for(int i = 1; i < n; i++)
{
int v =
Find_Min();
if (v ==
-1) break;
used[v] = 1;
for(int j = 0; j < g[v].size(); j++)
{
int to =
g[v][j].first;
int cost
= g[v][j].second;
if
(!used[to]) Relax(v,to,cost);
}
}
}
int main(void)
{
scanf("%d
%d",&t,&n);
g.resize(n+1);
for(i = 0; i
< t; i++)
{
scanf("%d
%d %d",&b,&e,&w);
g[b].push_back(make_pair(e,w));
g[e].push_back(make_pair(b,w));
}
Dijkstra();
printf("%d\n",dist[n]);
return 0;
}