描述
All one knows Jesse live in the city , but he must come to Xiasha twice in a week. The road is too long for him to go . But he is so much resolute that nothing can prevent him from coming . More, Jesse must take many bus to come , the length of road is different. So, Jesse think : can I take the shortest road to save time ?
Now , the problem is puting on you , can you help him to calculate the shortest length?
Is it easy? Just do it!
输入
The input has several test cases. The first line of each case has two number n,m (1 <= n,m <= 200 ). n means have n bus stations 1th,2th,....nth . m means have m roads. Then following next m lines ,each line have 3 integer a,b,c which means the length between a and b bus station is c(0 < c < 2000).
Then a line with two integer s,t,means the start and end bus station.
输出
For the given start and end bus station ,output the shortest lenth between s and t in one line.
If the road not exists,output -1.
样例输入
3 3
1 2 3
1 3 10
2 3 11
1 3
3 1
2 3 1
1 2
样例输出
10
-1
分析:
弗洛伊德算法的简单应用
代码:
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
int k,a,b,c,start,end1,i,j;
int e[205][205];
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
if(i==j)
e[i][j]=0;
else
e[i][j]=0x3f3f3f3f;
for(i=1; i<=m; i++)
{
scanf("%d%d%d",&a,&b,&c);
e[a][b]=e[b][a]=min(c,e[b][a]);//用于对输入的值进行判断,找出输入的时候的两点间的距离的最小值,无向图
}
scanf("%d%d",&start,&end1);
//应用三个for循环,弗洛伊德的关键步骤
for(k=1; k<=n; k++)
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
if(e[i][j]>e[i][k]+e[k][j])
e[i][j]=e[i][k]+e[k][j];
if(e[start][end1]!=0x3f3f3f3f)
printf("%d\n",e[start][end1]);
else
printf("-1\n");
}
return 0;
}