07-图4 哈利·波特的考试

在这里插入图片描述
在这里插入图片描述

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.小结

在这里插入图片描述
在这里插入图片描述

  1. 注意,要使用Floyd算法 计算任意两点之间的最短距离,而Floyd算法中使用了邻接矩阵,所以在构建图时,使用邻接矩阵构建图。
  2. 注意代码中如何找最大、最小值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值