前言:
该题利用Floyd算法,在这里根据视频里的建图思想来写
关键点:
1、建图,先定义边,在定义图,再根据题目要求建图插边
细节:题目中的结点下标从1开始,所以在插边时,要将结点--;
for (V=0; V<Graph->Ne; V++)
{
scanf("%d%d%d", &E->V1, &E->V2, &E->Weight);
E->V1--; E->V2--;
InsertEdge(Graph, E);
}
2、 如何找出最适合的动物,再利用Floyd算法找出任意两条边的最小值时,再遍历一次结点,找所有结点里花费最大的,再从所有花费最大中找出最少的,那么该结点即为最适合的结点。
for (i=0; i<Graph->Nv; i++)
{
MaxDist = FindMax(D, i, Graph->Nv);
if (MaxDist == INFINITY)
{
printf("0");
return ;
}
if (MaxDist<MinDist)
{
MinDist = MaxDist;
Animal = i+1;
}
}
3、当在FindMax中找该结点花费最大的时,要注意别跟自己到自己的结点比较大小,因为自己到自己的结点一直都置为最大初始值,这样比较导致所有结点的最大花费均为自己到自己的最大初始值。
for (j=0; j<N; j++)
{
if (i!=j&&D[i][j]>MaxDist)
MaxDist = D[i][j];
}
完整代码:
# include <stdio.h>
# include <stdlib.h>
# define INFINITY 200
# define MaxSize 200
typedef int WeightType;
typedef int Vertex;
typedef struct ENode *Edge;
struct ENode{
Vertex V1, V2;
WeightType Weight;
};
typedef struct GNode *MGraph;
struct GNode{
WeightType G[MaxSize][MaxSize];
int Nv;
int Ne;
};
MGraph CreateGraph(int VertexNum)
{
Vertex V, W;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct GNode));
Graph->Ne = 0;
Graph->Nv = VertexNum;
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][E->V1] = E->Weight;
}
MGraph BuildGraph()
{
Vertex V, W;
Edge E;
int Nv;
scanf("%d", &Nv);
MGraph Graph = CreateGraph(Nv);
scanf("%d", &Graph->Ne);
if (Graph->Ne!=0)
{
E = (Edge)malloc(sizeof(struct ENode));
for (V=0; V<Graph->Ne; V++)
{
scanf("%d%d%d", &E->V1, &E->V2, &E->Weight);
E->V1--; E->V2--;
InsertEdge(Graph, E);
}
}
return Graph;
}
void Floyd(MGraph Graph, WeightType D[][MaxSize])
{
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];
}
}
}
}
}
WeightType FindMax(WeightType D[][MaxSize], Vertex i, int N)
{
WeightType MaxDist = 0;
Vertex j;
for (j=0; j<N; j++)
{
if (i!=j&&D[i][j]>MaxDist)
MaxDist = D[i][j];
}
return MaxDist;
}
void FindAnimal(MGraph Graph)
{
WeightType D[MaxSize][MaxSize], MinDist = INFINITY, MaxDist=0;
Vertex Animal, i;
Floyd(Graph, D);
for (i=0; i<Graph->Nv; i++)
{
MaxDist = FindMax(D, i, Graph->Nv);
if (MaxDist == INFINITY)
{
printf("0");
return ;
}
if (MaxDist<MinDist)
{
MinDist = MaxDist;
Animal = i+1;
}
}
printf("%d %d\n", Animal, MinDist);
}
int main()
{
MGraph G = BuildGraph();
FindAnimal(G);
return 0;
}