题目汇总
浙江大学数据结构MOOC-课后习题-拼题A-代码分享-2024
题目描述
心路历程
当我看到慕课上对这题的简介写的是:
不过实现起来还是颇有码量的,有时间就尝试一下。
我甚至在想要不要在距离图书馆闭馆仅2个小时的时候,挑战这道题(鼠鼠我主打的就是一个菜T_T)
但看了看题解发现,这题确实不难好吧(手动滑稽)
思路也比较清晰
距离给自己设定的DDL还有6天,希望能把课后习题给肝完qaq
代码展示
#include <deque>
#include <cmath>
#include <cstdlib>
#include <iostream>
#define MAXSIZE 1000
/* 顶点 */
typedef int vertex;
/* 边 */
struct ENode
{
vertex V1, V2;
};
typedef ENode* ptrToENode;
typedef ptrToENode Edge;
/* 邻接表的链表节点 */
struct AdjNode
{
vertex AdjV; /* 邻接点编号 */
AdjNode* next;
};
typedef AdjNode* ptrToAdjNode;
/* 邻接表的表头数组 */
typedef struct VNode
{
ptrToAdjNode FirstEdge;
vertex data; //存储结点编号,编号 = 数组下标 + 1
}AdjList[MAXSIZE];
/* 图的定义 */
struct GNode
{
int Nv; /* 顶点数 */
int Ne; /* 边数 */
AdjList G; //邻接表
};
typedef GNode* ptrToGNode;
typedef ptrToGNode LGraph;
/* 创建并初始化一个图 */
LGraph creatGraph(int Nv)
{
vertex V, W;
LGraph graph = (LGraph)malloc(sizeof(GNode));
graph->Nv = Nv;
std::cin >> graph->Ne;
for (int i = 0; i < graph->Nv; i++)
{
graph->G[i].data = i + 1;
graph->G[i].FirstEdge = NULL;
}
return graph;
}
/* 向图中插入一条边 */
void insertEdge(LGraph Graph, Edge E)
{
vertex V = E->V1;
vertex W = E->V2;
/* 为W建立新的邻接点空间,并将其插到V的表头 */
ptrToAdjNode newNode = (ptrToAdjNode)malloc(sizeof(AdjNode));
newNode->AdjV = W;
newNode->next = Graph->G[V - 1].FirstEdge;
Graph->G[V - 1].FirstEdge = newNode;
/* 为V建立新的邻接点空间,并将其插到W的表头 */
newNode = (ptrToAdjNode)malloc(sizeof(AdjNode));
newNode->AdjV = V;
newNode->next = Graph->G[W - 1].FirstEdge;
Graph->G[W - 1].FirstEdge = newNode;
}
LGraph buildGraph()
{
int N;
std::cin >> N;
/* 创建图并初始化顶点 */
LGraph Graph = creatGraph(N);
vertex V, W;
/* 建立边 */
for (int i = 0; i < Graph->Ne; i++)
{
std::cin >> V >> W;
ptrToENode Edge = (ptrToENode)malloc(sizeof(ENode));
Edge->V1 = V;
Edge->V2 = W;
insertEdge(Graph, Edge);
}
return Graph;
}
int visit[MAXSIZE] = { 0 }; //结点为V,visit[V - 1]为0表示,结点V没被访问
int BFS(LGraph Graph, vertex V)
{
for (int i = 0; i < MAXSIZE; i++)
{
visit[i] = 0;
}
if (visit[V - 1] != 0) return 0;
visit[V - 1] = 1;
int count = 1;
int level = 0;
vertex tail; //下一层访问的最后一个节点
vertex last = V; //本层访问的最后一个节点
std::deque<vertex> deque;
deque.push_back(V);
while (!deque.empty())
{
V = deque.front();
deque.pop_front();
/* 遍历V的所有邻接节点 */
for (ptrToAdjNode W = Graph->G[V - 1].FirstEdge; W; W = W->next)
{
if (visit[W->AdjV - 1] == 0)
{
visit[W->AdjV - 1] = 1;
count++;
deque.push_back(W->AdjV);
tail = W->AdjV;
}
}
if (V == last)
{
level++;
last = tail;
}
if (level == 6) return count;
}
return count;
}
void SDS(LGraph Graph)
{
for (int i = 0; i < Graph->Nv; i++)
{
int count = BFS(Graph, Graph->G[i].data);
double rate = (double)count / Graph->Nv;
if(i == Graph->Nv - 1)
printf("%d: %.2f%%", Graph->G[i].data, rate * 100);
else
printf("%d: %.2f%%\n", Graph->G[i].data, rate * 100);
}
}
int main()
{
LGraph Graph = buildGraph();
SDS(Graph);
return 0;
}