void FindAnimal(MGraph Graph)
{
Floyd(Graph,D);
MinDist=INFINITY;
for(i=0;i<Graph->Nv;i++)
{
MaxDist=FindMaxDist(D,i,Graph->Nv);
if(MaxDist==INFINITY)
{cout<<0<<endl;
return;
}
if(MinDist>MaxDist)//找到最长距离更小的动物
{
MinDist=MaxDist);
Animal=i+1;//更新距离,记录编号
}
cout<<Animal<<MinDist<<endl;
}
WeightType FindMaxDist(WeightType D[][MaxVertexNum],Vertex i,int N)
{
WeightType MaxDist;
Vertex j;
MaxDist=0;
for(j=0;j<N;j++)
if(i!=j&&D[i][j]>MaxDist)//找出i到其他动物j的最长距离
MaxDist=D[i][j];
return MaxDist;
}
模块的引用与裁剪
#define MaxVertexNum 100//最大顶点数设为100
#define INFINITY//设为双字节无符号整数的最大值65535
typedef int Vertex;
typedef int Weight;
typedef struct ENode *PtrToENode;//边的定义
struct ENode{
Vertex V1,V2;//有向图<V1,V2>
WeightType Weight;//权重
};
typedef PtrToENode Edge;//圆结点的定义
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;//顶点数
int Ne;//边数
WeightType G[MaxVertexNum][MaxVertexNum];//临接矩阵
};
typedef PtrToGNode MGraph;//以临接矩阵存储的图类型
MGraph CreateGraph(int VertexNum)
{//初始化一个有VertexNum个顶点但没有边的图
Vertex V,W;
MGraph Graph;
Graph=(MGraph)malloc(sizeof(struct GNode));//建立图
Graph->Nv=VertexNum;
Graph->Ne=0;
for(v=0;v<Graph->Nv;v++)//初始化临接矩阵
for(w=0;w<Graph->Nv;w++)
Graph->G[V][W]=INFINITY;
return Graph;
}
void InsertEdge(MGraph Graph,Edge E)
{
Graph->G[E->V1][E->V2]=E->Weight;
Graph->G{E->V2][V->V1]=E->Weight;
}
MGraph BuildGraph()
{
MGraph Graph;
Edge E;
int Nv,i;
cin>>Nv;//读入顶点个数
Graph=CreateGraph(Nv);初始化有Nv个顶点但没有边的图
cin>>Graph->Ne;//读入边数
if(Graph->Ne!=0){
E=(Edge)malloc(sizeof(struct ENode));
for(i=0;i<Graph->Ne;i++)
{ cin>>E->V1>>E->V2>>Weight;
E->V1--;E->V2--;
InsertEdge(Grapg,E);
}
}
return Graph;
}
void Floyd(MGraph Graph,WeightType D[][MaxVertexNum])
{ vertex i,j,k;
for(i=0;i<Graph->Nv;i++)//初始化
for(j=0;j<Graph->Nv;j++)
D[i][j]=Graph->G[i][j];
for(k=0;k<Graph->Nv;k++)
for(i=0;i<Graph->Nv;i++)
for(j=0;j<Graph->Nv;j++)
if(D[i][k]+D[k][j]<D[i][j]
D[i][j]=D[i][k]+D[k][j];
}
最后编个主程序
int main()
{ MGraph G=BuildGraph();
FindAnimal(G);
return 0;
}