医院选址问题
在五个村庄之中选一个建立医院,要求各个村庄往返路程越短越好,最好应该选在何处
有向网的邻接矩阵
0 13 M 4 M
13 0 15 M 5
M M 0 12 M
4 M 12 0 M
M M 6 3 0
*/
#include<stdio.h>
const int N = 5;
const int MaxValue = 100;
char vertex[N] ={'A','B','C','D','E'};
int arc[N][N] = {{0,13,MaxValue,4,MaxValue},{13,0,15,MaxValue,5},{MaxValue,MaxValue,0,12,MaxValue},
{4,MaxValue,12,0,MaxValue},{MaxValue,MaxValue,6,3,0}};
int dist[N][N] = {0}; //存储任意俩个顶点最短路径
int Center()
{
int wayCost,minCost = MaxValue,index;
int i,j,k;
for(k=0;k<N;k++) //依次求每个顶点往返代价
{
wayCost = 0;
for(i=0;i<N;i++) //求i到其他顶点路径长度之和
wayCost = wayCost + dist[i][k];
for(j=0;j<N;j++)
wayCost = wayCost + dist[k][j];
if(wayCost < minCost)
{
minCost = wayCost;
index = k; //k为当前中心点
}
}
return index;
}
void Floyd()
{
int i,j,k;
for(i=0;i<N;i++)
for(j=0;j<N;j++)
{
dist[i][j] = arc[i][j];
}
for(k=0;k<N;k++)
for(i=0;i<N;i++) //顶点i、j是否经过顶点k
for(j=0;j<N;j++)
if(dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
int main()
{
int minPoint; //储存中心点下标
Floyd();
minPoint = Center();
printf("中心点应该在%c处\n",vertex[minPoint]);
return 0;
}