拓扑序|Topological Order_1146

本文深入探讨了拓扑排序算法的原理与应用,通过详细解释拓扑序的定义及其在有向无环图中的作用,提供了算法的具体实现步骤。文章还包含了一个基于2018年研究生入学考试问题的实例,旨在帮助读者理解如何通过编程测试给定的选项是否符合拓扑排序的要求。

描述

This is a problem given in the Graduate Entrance Exam in 2018: Which of the following is NOT a topological order obtained from the given directed graph? Now you are supposed to write a program to test each of the options.

image

指定输入

Each input file contains one test case. For each case, the first line gives two positive integers N (≤ 1,000), the number of vertices in the graph, and M (≤ 10,000), the number of directed edges. Then M lines follow, each gives the start and the end vertices of an edge. The vertices are numbered from 1 to N. After the graph, there is another positive integer K (≤ 100). Then K lines of query follow, each gives a permutation of all the vertices. All the numbers in a line are separated by a space.

指定输出

Print in a line all the indices of queries which correspond to “NOT a topological order”. The indices start from zero. All the numbers are separated by a space, and there must no extra space at the beginning or the end of the line. It is graranteed that there is at least one answer.

输入样例

6 8
1 2
1 3
5 2
5 4
2 3
2 6
3 4
6 4
5
1 5 2 3 6 4
5 1 2 6 3 4
5 1 2 3 6 4
5 2 1 6 3 4
1 2 3 4 5 6

输出样例

3 4

分析

这道题我做得答案错了,但思路是正确的,程序还有bug,鉴于现在时间已经很晚了,先把过程记录下来,以后在做修改

分析点一:拓扑序的定义

拓扑序:若不存在回路即为有向无环图,所有节点可排成线性序列,使得节点的前驱节点都排在该节点的前面

分析点二:拓扑序算法

  • 首先扫描每一个节点,如果入度等于0(即无前驱节点),则入队
  • 当队列不为空时,出队,接下来处理与这个顶点相邻接的点
  • 找到所有与当前节点相邻接的点,删除边,即入度减一,如过入度为0,加入到队列中 image

分析点三:c++实现的拓扑排序

/* 邻接表存储 - 拓扑排序算法 */
 
bool TopSort( LGraph Graph, Vertex TopOrder[] )
{ /* 对Graph进行拓扑排序,  TopOrder[]顺序存储排序后的顶点下标 */
    int Indegree[MaxVertexNum], cnt;
    Vertex V;
    PtrToAdjVNode W;
       Queue Q = CreateQueue( Graph->Nv );
  
    /* 初始化Indegree[] */
    for (V=0; V<Graph->Nv; V++)
        Indegree[V] = 0;
         
    /* 遍历图,得到Indegree[] */
    for (V=0; V<Graph->Nv; V++)
        for (W=Graph->G[V].FirstEdge; W; W=W->Next)
            Indegree[W->AdjV]++; /* 对有向边<V, W->AdjV>累计终点的入度 */
             
    /* 将所有入度为0的顶点入列 */
    for (V=0; V<Graph->Nv; V++)
        if ( Indegree[V]==0 )
            AddQ(Q, V);
             
    /* 下面进入拓扑排序 */ 
    cnt = 0; 
    while( !IsEmpty(Q) ){
        V = DeleteQ(Q); /* 弹出一个入度为0的顶点 */
        TopOrder[cnt++] = V; /* 将之存为结果序列的下一个元素 */
        /* 对V的每个邻接点W->AdjV */
        for ( W=Graph->G[V].FirstEdge; W; W=W->Next )
            if ( --Indegree[W->AdjV] == 0 )/* 若删除V使得W->AdjV入度为0 */
                AddQ(Q, W->AdjV); /* 则该顶点入列 */ 
    } /* while结束*/
     
    if ( cnt != Graph->Nv )
        return false; /* 说明图中有回路, 返回不成功标志 */ 
    else
        return true;
}

我的代码

v, e = map(int, input().split(" "))
v_set = set({})
v_map = dict({})
for i in range(e):
    a, b = map(int, input().split(" "))
    v_set.add(b)
    if v_map.get(a) is None:
        temp = list()
        temp.append(b)
        v_map[a] = temp
    else:
        v_map[a].append(b)

res = []
v_container = []

for j in range(1, v + 1):
    if j not in v_set:
        v_container.append(j)

if len(v_container) > 0:
    p = set(v_container)
    res.append(p)

while True:
    t = []
    while len(v_container) > 0:
        temp = v_container.pop()
        s = v_map.pop(temp)
        t.append(s)

    v_set = set({})
    v_container = []
    for value in v_map.values():
        for n in value:
            v_set.add(n)
    temp_set = set({})
    if len(v_set) != 0:
        for d in t:
            for e in d:
                if e not in v_set and len(v_set) != 0:
                    temp_set.add(e)
        v_container = list(temp_set)
    else:
        for d in t:
            for e in d:
                temp_set.add(e)
        res.append(temp_set)

    if len(v_container) == 0:
        break

    po = set(v_container)
    res.append(po)

h = int(input())
cnt = 0
result_set = set({})
for g in range(h):
    s = list(map(int, input().split(" ")))
    cnt += 1
    count = 0
    for k in res:
        for l in range(len(k)):
            if s[count + l] not in k:
                result_set.add(cnt - 1)
                break
        count = count + len(k)

result_set = list(result_set)
for z in range(len(result_set)):
    if z == len(result_set) - 1:
        print(result_set[z], end="")
    else:
        print(result_set[z], end=" ")

??正文结束??
<think>我们被要求使用中文回答,并且需要遵循严格的格式要求。 用户的问题是关于networkx库中`nx.topological_sort()`函数的使用和示例。 根据引用,我们知道NetworkX是一个用于复杂网络的Python库,而拓扑是有向无环图(DAG)中节点的一种线性排,使得对于每一条有向边(u, v),节点u都出现在节点v之前。 我们将按照以下步骤回答: 1. 解释拓扑的概念。 2. 介绍`nx.topological_sort()`函数的基本用法。 3. 提供一个完整的示例代码,包括创建有向图、进行拓扑以及输出结果。 4. 注意:在示例代码中,我们将使用NetworkX创建一个小型的有向无环图。 同时,根据系统指令,我们需要生成相关问题。 注意:在回答中,我们引用了NetworkX官方文档(引用[1]和引用[3]),因此会在适当的地方添加引用标识。 开始回答:</think>### NetworkX 中 `nx.topological_sort()` 函数的使用与示例 拓扑是针对**有向无环图(DAG)** 的节点线性排算法,使得对于任意有向边 \((u \to v)\),节点 \(u\) 总出现在节点 \(v\) 之前。`nx.topological_sort()` 是 NetworkX 库中实现该算法的核心函数[^1]。 --- #### **基本用法** ```python import networkx as nx # 创建有向图 G = nx.DiGraph() edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")] G.add_edges_from(edges) # 拓扑 sorted_nodes = list(nx.topological_sort(G)) print(sorted_nodes) # 输出:['A', 'C', 'B', 'D'] 或 ['A', 'B', 'C', 'D'](合法排不唯一) ``` - **输入要求**:图必须为有向无环图(DAG),若图含环会抛出 `NetworkXUnfeasible` 异常。 - **返回值**:节点的拓扑列表(可能有多个合法结果,函数返回其中一种)。 --- #### **完整示例:课程依赖关系排** 假设课程依赖关系如下: - 数据结构依赖编程基础 - 算法依赖数据结构 - 机器学习依赖算法和数学 ```python import networkx as nx # 定义课程依赖图 G = nx.DiGraph() G.add_edges_from([ ("编程基础", "数据结构"), ("数据结构", "算法"), ("算法", "机器学习"), ("数学", "机器学习") ]) # 拓扑(确保无循环依赖) try: course_order = list(nx.topological_sort(G)) print("课程学习顺:", course_order) except nx.NetworkXUnfeasible: print("图中存在循环依赖,无法排!") # 输出示例:['数学', '编程基础', '数据结构', '算法', '机器学习'] ``` --- #### **关键注意事项** 1. **检测环**:排前可用 `nx.is_directed_acyclic_graph(G)` 验证是否为 DAG。 2. **多结果处理**:若需所有可能排,使用 `list(nx.all_topological_sorts(G))`。 3. **性能**:时间复杂度 \(O(V+E)\)(\(V\) 为节点数,\(E\) 为边数),适合大型图处理[^3]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值