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
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
Sample Output
90
Hint
INPUT DETAILS:
There are five landmarks.
OUTPUT DETAILS:
Bessie can get home by following trails 4, 3, 2, and 1.
题目链接
https://vjudge.net/contest/280125#problem/A
题目大意
N个点,T段距离,求出1到N的最短路。
注意
需要判断是否有重边,两点之间的路,可能不只有一条。
数据范围
N (2 <= N <= 1000)
T (1 <= T <= 2000)
每段距离 1~100
解题思路
最短路问题,翻书后首先尝试用Floyd-Warshall
但是超时了
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int a[2005][2005];
int main()
{
int n,t,x,y;
memset(a,0x3f3f3f3f,sizeof(a));
scanf("%d %d",&t,&n);
for(int i = 1;i <= t;i++){
scanf("%d %d",&x,&y);
scanf("%d",&aa);
if(aa < a[x][y]) a[x][y] = aa;
a[y][x] = a[x][y];
}
for(int k = 1;k <= n;k++)
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++)
if(a[i][k] < 0x3f3f3f3f&&a[k][j] < 0x3f3f3f3f&&a[i][j]>a[i][k]+a[k][j])
a[i][j] = a[i][k] + a[k][j];
printf("%d\n",a[1][n]);
return 0;
}
尝试优化,但是wa了,优化过后的算法有问题
然后第二节介绍了Diskstra,用Diskstra就过了。
书上讲两种方法进行了对比
---------------Floyd ——— Diskstra
空间复杂度 O(N²) ---- O(M)
时间复杂度 O(N³) -----O((M + N)logN )
负权 可以解决 —— 不能解决
解决代码
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int a[1005][1005];
int dis[1005],book[1005];
int main()
{
int n,t,x,y,min,v,j,u,aa;
book[1] = 1;
memset(a,0x3f3f3f3f,sizeof(a));
scanf("%d %d",&t,&n);
for(int i = 1;i <= n;i++)
a[i][i] = 0;
for(int i = 1;i <= t;i++){
scanf("%d %d",&x,&y);
scanf("%d",&aa);
if(aa < a[x][y]) a[x][y] = aa;
a[y][x] = a[x][y];
}
for(int i = 1;i <= n;i++){
dis[i] = a[1][i];
}
for(int i = 1;i <= n - 1;i++)
{
min = 0x3f3f3f3f;
for(j = 1;j <= n;j++)
{
if(book[j] == 0&&dis[j] < min){
min = dis[j];
u = j;
}
}
book[u] = 1;
for(v = 1;v <= n;v++){
if(a[u][v] < 0x3f3f3f3f){
if(dis[v] > dis[u] + a[u][v])
dis[v] = dis[u] + a[u][v];
}
}
}
printf("%d\n",dis[n]);
return 0;
}