ACM刷题之路(五)最短路 Dijkstra POJ2387

2023-07-31 15:27:43 浏览数 (2)

题目网址:http://poj.org/problem?id=2387

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

代码语言:javascript复制
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

Sample Output

代码语言:javascript复制
90

题意

就是第一行n,m

n代表有几条路,m代表1到m

求最短路径

先介绍一下Dijkstra算法

大概意思就是先找出1到各个结点的距离,保存在dis数组;然后在这些结点中找出与1距离最小的结点,判断它能不能作为中转站,使它作为中转站的情况下使得距离变得更小。

比如1到2的路是10,2到3的路是20,1到3的距离是50;先遍历从1开始的路,即dis[1]=0,dis[2]=10,dis[3]=50,然后到2的距离最小(因为1到1的距离是0已经确定),所以判断把2作为中转站的情况下能否使得1到别的结点的距离变得更小,最后更新1到3的距离是30,即dis[3]=30。这是我个人理解的Dijkstra算法。

ps:vis数组代表判断是否被访问过,有一股回溯法的感觉。


代码语言:javascript复制
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAX 9999999
using namespace std;

int u, v, n, dis[1111], vis[1111], ma[1111][1111];
//有u条路,1到v个点 dis表示0到dis[i]的最短距离 
//vis判断是否访问 ma数组储蓄各点之间的路长
int max(int x, int y){
	if (x > y) return x;
	return y;
}
void dijk(){
	int i, j, k, mini;
	for (i = 1; i <= v; i  ){
		dis[i] = ma[1][i];		//首先让1可以通的路长赋值给dis数组
	}
	for (i = 1; i <= v; i  ){
		mini = MAX;
		for (j = 1; j <= v; j  ) {//选出未确定最短路径中最短的结点
			if (!vis[j] && dis[j] < mini){
				mini = dis[j];
				k = j;//k就是最短的结点
			}
		}
		vis[k] = 1;		//设置k被访问过
		for (j = 1; j <= v; j  ){
			if (dis[j] > dis[k]   ma[k][j]) {//如果k当中转站的距离比原来的小
				dis[j] = dis[k]   ma[k][j];
			}
		}
	}
}
int main(){
	int i, j;
	while (cin >> u >> v){
		n = 0;
		for (i = 0; i <= v; i  ){
			for (j = 0; j <= v; j  ){
				ma[i][j] = MAX;//所有数初始化为无穷大
			}
			ma[i][i] = 0;      //i到i的距离为0
			vis[i] = 0;			//表示i结点还没有被访问过
			dis[i] = MAX;			//初始化0到i结点的距离为无穷
		}
		for (i = 1; i <= u; i  ){
			int a, b, len;
			cin >> a >> b >> len;
			n = max(max(n, a), b);		//n是要求最大的点,以便后面搜索
			if (ma[a][b] > len) {		//如果len小于a到b的距离,即为最优解
				ma[a][b] = ma[b][a] = len;
			}
		}
		dijk();
		printf("%dn", dis[v]);
	}
	return 0;
}

0 人点赞