题目意思
有n个城镇,编号为0~n-1,m条道路,从一个城镇到另一个城镇有多条路,现在问你从一个城镇到另一个城镇的最短距离是多少。如果没有路就输出-1。
解题思路
这就是一道简单的最短路问题,用Floyd算法或dijkstra算法都行。其中要注意的是,城镇之间的路是双向的,下边刷数组的时候要刷双向的。
代码部分
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <queue>
using namespace std;
const int INF=0x3f3f3f;
int map[210][210];///存储两城镇之间的距离
int n,m;
void floyd()
{
for(int k=0; k<n; k++)
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
map[i][j]=min(map[i][j],map[i][k]+map[k][j]);
}
int main()
{
int s,t;
int a,b,x;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
{
if(i==j)
map[i][j]=0;///城镇自身距离为0
else
map[i][j]=INF;
}
while(m--)
{
scanf("%d%d%d",&a,&b,&x);
if(map[a][b]>x)
map[a][b]=map[b][a]=x;///双向道路,就这一点WA了一次
}
scanf("%d%d",&s,&t);
floyd();
if(map[s][t]==INF)
printf("-1\n");
else
printf("%d\n",map[s][t]);
}
return 0;
}