浙江大学数据结构MOOC-课后习题-第七讲-图4 哈利·波特的考试

题目汇总
浙江大学数据结构MOOC-课后习题-拼题A-代码分享-2024

题目描述

代码展示

照着教程视频来的,没啥好说的捏

cpp 复制代码
#include <cstdlib>
#include <iostream>

#define MAXSIZE 100
#define IFINITY 65535
typedef int vertex;
typedef int weightType;

/* 边 */
struct ENode
{
	vertex V1, V2;
	weightType weight;
};
typedef ENode* ptrToENode;
typedef ptrToENode Edge;

/* 图结点 */
struct GNode
{
	int Nv;	/* 节点数 */
	int Ne;	/* 边数 */
	weightType G[MAXSIZE][MAXSIZE];	/* 邻接矩阵 */
};
typedef GNode* ptrToGNode;
typedef ptrToGNode MGraph;

MGraph creatGraph()
{	
	vertex V, W;
	MGraph G = (MGraph)malloc(sizeof(GNode));
	G->Ne = 0;
	std::cin >> G->Nv;

	for (V = 0; V < G->Nv; V++)
	{
		for (W = 0; W < G->Nv; W++)
		{
			G->G[V][W] = IFINITY;
		}
	}
	return G;
}

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 G = creatGraph();
	
	//插入边
	std::cin >> G->Ne;
	if (G->Ne != 0)
	{
		Edge E = (Edge)malloc(sizeof(ENode));
		for (int i = 0; i < G->Ne; i++)
		{
			std::cin >> E->V1 >> E->V2 >> E->weight;
			E->V1--;
			E->V2--;
			insertEdge(G, E);
		}
	}
	return G;
}

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 findMaxDist(MGraph Graph, weightType D[][MAXSIZE], vertex i)
{
	weightType maxDist;
	vertex j;

	maxDist = 0;
	
	for (j = 0; j < Graph->Nv; j++)
	{
		if (D[i][j] > maxDist && i != j)
			maxDist = D[i][j];
	}
	return maxDist;
}
void findAnimal(MGraph G)
{	
	
	weightType D[MAXSIZE][MAXSIZE], maxDist, minDist;
	vertex animal, i;
	

	/* 利用Floyd求出任意两点间的最短路径长度 */
	floyd(G, D);
	
	/* 找出每行中的最大值, 然后从所有最大值中找出最小值 */
	minDist = IFINITY;
	for (i = 0; i < G->Nv; i++)
	{	
		maxDist = findMaxDist(G, D, i);
		if (maxDist == IFINITY)
		{
			std::cout << "0";
			return;
		}
		if (maxDist < minDist)
		{
			minDist = maxDist;
			animal = i + 1;
		}
	}
	std::cout << animal << ' ' << minDist;
}
int main()
{
	MGraph G = buildGraph();
	findAnimal(G);
	return 0;
}

心路历程

感觉有点懈怠了...

相关推荐
夏末秋也凉8 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
王老师青少年编程8 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
liuyuzhongcc11 小时前
List 接口中的 sort 和 forEach 方法
java·数据结构·python·list
计算机小白一个13 小时前
蓝桥杯 Java B 组之背包问题、最长递增子序列(LIS)
java·数据结构·蓝桥杯
卑微的小鬼13 小时前
数据库使用B+树的原因
数据结构·b树
cookies_s_s13 小时前
Linux--进程(进程虚拟地址空间、页表、进程控制、实现简易shell)
linux·运维·服务器·数据结构·c++·算法·哈希算法
醉城夜风~15 小时前
[数据结构]双链表详解
数据结构
gyeolhada15 小时前
2025蓝桥杯JAVA编程题练习Day5
java·数据结构·算法·蓝桥杯
阿巴~阿巴~15 小时前
多源 BFS 算法详解:从原理到实现,高效解决多源最短路问题
开发语言·数据结构·c++·算法·宽度优先
刃神太酷啦17 小时前
堆和priority_queue
数据结构·c++·蓝桥杯c++组