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.
Hint
INPUT DETAILS:
There are five landmarks.
OUTPUT DETAILS:
Bessie can get home by following trails 4, 3, 2, and 1.
这题直接用Google翻译一下,一眼就能看出来是个最短路的问题。我记得最短路好像是大一上学期结训之前几天说的,但是那时候在划水摸大鱼(bushi, 然后我就去复习了一下最短路的算法,正好趁着这个题来复习一下迪杰斯特拉算法。
Dijkstra算法的思想感觉还是很简单的,就是在未标记过的节点里面找想要达到目标点的最短路径来不断地更新。主要用来处理单源最短路问题,这题的hint很明显的告诉了你就是个求单源最短路的问题
代码附上:
#include <cstdio>
#include <iostream>
#define inf 0x3f3f3f3f
using namespace std ;
const int N = 1008 ;
int mp[N][N] ;
bool vis[N] ;
int dis[N] ;
int t, n ;
void init() {
for (int i = 1 ; i <= n ; i ++ ) {
for (int j = 1 ; j <= i ; j ++) {
mp[i][j] = inf, mp[j][i] = inf ;
}
}
}
void dijkstra() {
vis[1] = true ; //首先要把起始位置1给标记
for (int i = 1 ; i < n ; i ++) {
int min = inf ;
int pos = 1 ;
for (int j = 1 ; j <= n ; j ++) { //这层for循环用来找最小的dis
if (!vis[j] && min > dis[j])
min = dis[j], pos = j ;
}
vis[pos] = true ;
for (int j = 1 ; j <= n ; j ++) { //这层for循环用来更新边
if (!vis[j] && mp[pos][j] + dis[pos] < dis[j]) {
dis[j] = mp[pos][j] + dis[pos] ;
}
}
}
cout << dis[n] << '\n' ;
}
int main() {
cin >> t >> n ;
init() ; //初始化
while (t --) {
int u, v, w ;
cin >> u >> v >> w ;
if (w < mp[u][v]) //存图,加了这个条件语句是为了处理重边问题
mp[u][v] = w, mp[v][u] = w ;
}
for (int i = 1 ; i <= n ; i ++ ) { //也是初始化,这里的mp[][]不仅代表了边权值得大小,另一
dis[i] = mp[1][i] ; //方面也代表了当前的边存不存在;同理,这里的更新dis不仅代表
} //了到达该位置的最短路,同时也代表了能不能从起始点到达目标点
dijkstra() ;
return 0 ;
}