6 11
3 4 70
1 2 1
5 4 50
2 6 50
5 6 60
1 3 70
4 6 60
3 6 80
5 1 100
2 4 60
5 2 80
1.代码
#include<stdio.h>
#define INFINITY 65535
#define MaxVertexNum 100
typedef int Vertex;
typedef int WeightType;
typedef struct ENode * PtrToENode;
struct ENode{
Vertex V1;
Vertex 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 N){
MGraph Graph;
Vertex V, W;
Graph = (MGraph)malloc(sizeof(struct GNode));
Graph->Nv = N;
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][E->V1] = E->Weight;
}
MGraph BuildGraph(){
MGraph Graph;
int Nv, i;
Edge E;
scanf("%d", &Nv);
Graph = CreateGraph(Nv);
scanf("%d", &(Graph->Ne));
if(Graph->Ne != 0){
E = (Edge)malloc(sizeof(struct ENode));
for(i=0; i<Graph->Ne; i++){
scanf("%d %d %d", &E->V1, &E->V2, &E->Weight);
E->V1--;
E->V2--;
InsertEdge(Graph, E);
}
}
return Graph;
}
//找每一行中的最大值
WeightType FindMaxDist(WeightType D[][MaxVertexNum], Vertex i, int N){
WeightType MaxDist;
Vertex j;
MaxDist = 0;
for(j=0; j<N; j++)
//if(D[i][j]!=INFINITY && D[i][j]>MaxDist){
if(i!=j && D[i][j]>MaxDist){
MaxDist = D[i][j];
//printf("i=%d, j=%d, D[i][j]=%d\n", i, j, D[i][j]);
}
return MaxDist;
}
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];
}
void FindAnimal(MGraph Graph){
WeightType D[MaxVertexNum][MaxVertexNum];
WeightType MaxDist, MinDist;
Vertex Animal, i;
Floyd(Graph, D);
MinDist = INFINITY;
for(i=0; i<Graph->Nv; i++){
MaxDist = FindMaxDist(D, i, Graph->Nv);
//printf("i=%d, MaxDist=%d\n", i, MaxDist);
if(MaxDist == INFINITY){
printf("0\n");
return;
}
if(MinDist > MaxDist){
MinDist = MaxDist;
Animal = i + 1;
}
}
printf("%d %d\n", Animal, MinDist);
}
int main(){
MGraph G = BuildGraph();
FindAnimal(G);
return 0;
}
2.小结
- 注意,要使用
Floyd算法
计算任意两点之间的最短距离,而Floyd算法
中使用了邻接矩阵,所以在构建图时,使用邻接矩阵构建图。 - 注意代码中如何找最大、最小值