告诉你各个城市之间的距离,让你求从某个城市到另一个城市的最短路径问题
因为从一个城市到另一个城市想要缩短距离,只能经过其他城市来缩短距离
</pre><pre code_snippet_id="1967318" snippet_file_name="blog_20161104_1_472332" name="code" class="cpp">#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<iomanip>
#define INF 99999999
using namespace std;
int city[6][6];
int main()
{
//建立城市之前的关系图,自身到自身距离为0,两个城市无法到达则为INF
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
{
if(i==j)
city[i][j]=0;
else city[i][j]=INF;
}
int x,y,r;
//输入题目给出的两个城市之间的距离
for(int i=1;i<=8;i++)
{
scanf("%d%d%d",&x,&y,&r);
city[x][y]=r;
}
for(int i=1;i<=4;i++) //经过几号顶点 来缩短路径
{ //从j号顶点到k号顶点的距离能否通过i号顶点作为中介缩短路程,如果可以,则更新两点之前的最短路程
for(int j=1;j<=4;j++)
{
for(int k=1;k<=4;k++)
{
if(city[j][k]>city[j][i]+city[i][k])//如果通过i点的中转,路径可以缩小,则更新两个城市之间的距离
city[j][k]=city[j][i]+city[i][k];
}
}
}
//打印出缩短后的路径,city[i][j]代表i点到j点的最短距离
for(int i=1;i<=4;i++)
{
for(int j=1;j<=4;j++)
{
printf("%d ",city[i][j]);
}
printf("\n");
}
return 0;
}
/*测试数据
1 2 2
1 3 6
1 4 4
2 3 3
3 1 7
3 4 1
4 1 5
4 3 12
程序运行效果
0 2 5 4
9 0 3 4
6 8 0 1
5 7 10 0
*/