思路:这个题直接用Floyed算法计算任意两点的距离,然后输出到'Z'距离最远并且有牛存在的牧区到Z的距离。还有一点就是如何把题目中的数据用邻接矩阵存储下来,可以把字母的ASCII-‘A’作为邻接矩阵的下标。
补充Floyed算法
Floyd-Warshall 算法用来找出每对点之间的最短距离。它需要用邻接矩阵来储存边,这个算法通过考虑最佳子路径来得到最佳路径。
注意单独一条边的路径也不一定是最佳路径。
- 从任意一条单边路径开始。所有两点之间的距离是边的权,或者无穷大,如果两点之间没有边相连。
- 对于每一对顶点 u 和 v,看看是否存在一个顶点 w 使得从 u 到 w 再到 v 比己知的路径更短。如果是更新它。
- 不可思议的是,只要按排适当,就能得到结果。
// dist(i,j) 为从节点i到节点j的最短距离 For i←1 to n do For j←1 to n do dist(i,j) = weight(i,j) For k←1 to n do // k为“媒介节点” For i←1 to n do if (i<>k) then For j←1 to n do if (i<>j) and(k<>j)then if (dist(i,k) + dist(k,j) < dist(i,j)) then // 是否是更短的路径? dist(i,j) = dist(i,k) + dist(k,j)
源代码:
/*
ID: supersnow0622
PROG: test
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int dist[101][101];
int main() {
ofstream fout ("test.out");
ifstream fin ("test.in");
int P;
cin>>P;
char a,b;
int c;
for(int i=0;i<101;i++)
for(int j=0;j<101;j++)
dist[i][j]=1000000;
for(int i=0;i<P;i++)
{
cin>>a>>b>>c;
if(c<dist[a-'A'][b-'A'])
{
dist[a-'A'][b-'A']=c;
dist[b-'A'][a-'A']=c;
}
}
for(int k=0;k<60;k++)
for(int i=0;i<60;i++)
if(i!=k)
{
for(int j=0;j<60;j++)
{
if(i!=j&&k!=j)
if(dist[i][k]+dist[k][j]<dist[i][j])
dist[i][j]=dist[i][k]+dist[k][j];
}
}
int min=1000000,record;
for(int i=0;i<25;i++)
if(dist[i][25]<min)
{
min=dist[i][25];
record=i;
}
cout<<(char)(record+'A')<<" "<<min;
return 0;
}