From d691739b31d83d4fc6732a1fc59e315ab7829c86 Mon Sep 17 00:00:00 2001 From: xusun0623 <45837271+xusun0623@users.noreply.github.com> Date: Tue, 3 Sep 2024 23:06:58 +0800 Subject: [PATCH] Create 2024_unique_topology_order.cpp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增2024年算法题 --- 2024_unique_topology_order.cpp | 57 ++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 2024_unique_topology_order.cpp diff --git a/2024_unique_topology_order.cpp b/2024_unique_topology_order.cpp new file mode 100644 index 0000000..e768c5f --- /dev/null +++ b/2024_unique_topology_order.cpp @@ -0,0 +1,57 @@ +#include +#include +#include + +#define MAXV 100 // 假设最大顶点数为100 + +typedef struct { + int numberVertices, numberEdges; // 图的顶点数和边数 + char VerticesList[MAXV]; // 顶点表 + int edge[MAXV][MAXV]; // 邻接矩阵 +} MGraph; + +// 判断图是否有唯一的拓扑序列 +int intquely(MGraph G) { + std::vector inDegree(G.numberVertices, 0); + std::queue q; + + // 计算每个顶点的入度 + for (int i = 0; i < G.numberVertices; ++i) { + for (int j = 0; j < G.numberVertices; ++j) { + if (G.edge[i][j] != 0) { + inDegree[j]++; + } + } + } + + // 找到所有入度为0的顶点并加入队列 + for (int i = 0; i < G.numberVertices; ++i) { + if (inDegree[i] == 0) { + q.push(i); + } + } + + std::vector topoOrder; + + while (!q.empty()) { + if (q.size() > 1) { // 入度为0的顶点不唯一 + return 0; + } + + int v = q.front(); + q.pop(); + topoOrder.push_back(v); + + for (int i = 0; i < G.numberVertices; ++i) { + if (G.edge[v][i] != 0) { + inDegree[i]--; + if (inDegree[i] == 0) { + q.push(i); + } + } + } + } + + // 若拓扑排序包含了所有顶点,则说明图有唯一的拓扑序列 + return (topoOrder.size() == G.numberVertices) ? 1 : 0; +}