http://www.lintcode.com/zh-cn/problem/topological-sorting/#

给定一个有向图,图节点的拓扑排序被定义为:

  • 对于每条有向边A--> B,则A必须排在B之前
  • 拓扑排序的第一个节点可以是任何在图中没有其他节点指向它的节点

找到给定图的任一拓扑排序

solution

Topological Sorting

Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.

For example, a topological sorting of the following graph is “5 4 2 3 1 0″. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 3 1 0″. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no in-coming edges).

Topological Sorting vs Depth First Traversal (DFS):
In DFS, we print a vertex and then recursively call DFS for its adjacent vertices. In topological sorting, we need to print a vertex before its adjacent vertices. For example, in the given graph, the vertex ‘5’ should be printed before vertex ‘0’, but unlike DFS, the vertex ‘4’ should also be printed before vertex ‘0’. So Topological sorting is different from DFS. For example, a DFS of the above graph is “5 2 3 1 0 4″, but it is not a topological sorting

Algorithm to find Topological Sorting:
We recommend to first see implementation of DFS here. We can modify DFSto find Topological Sorting of a graph. In DFS, we start from a vertex, we first print it and then recursively call DFS for its adjacent vertices. In topological sorting, we use a temporary stack. We don’t print the vertex immediately, we first recursively call topological sorting for all its adjacent vertices, then push it to a stack. Finally, print contents of stack. Note that a vertex is pushed to stack only when all of its adjacent vertices (and their adjacent vertices and so on) are already in stack.

引用自 http://www.geeksforgeeks.org/topological-sorting/

如果仅仅只是对DAG进行DFS,那么针对某一起始点(例如上图中的5)开始的DFS确实可以满足Topological sorting,但是当对该点DFS范围以外的其他点(例如上图中的4)再进行DFS时,很可能会出现不满足Topological sorting的情况。例如上图中,在4指向1的清凉下。那如何解决?

利用栈后进先出的性质,我们可以依次递归的将每一个vertex的adjacent vertices先入栈,vertex最后入栈,这样vertices的出栈顺序即满足Topological sorting,代码如下:

// Author: Jian-xin Zhou

/**
* Definition for Directed graph.
* struct DirectedGraphNode {
* int label;
* vector<DirectedGraphNode *> neighbors;
* DirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
/**
* @param graph: A list of Directed graph node
* @return: Any topological order for the given graph.
*/
vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) {
// write your code here
unordered_set<DirectedGraphNode*> unique;
stack<DirectedGraphNode*> st;
topologicalSort(graph, unique, st); vector<DirectedGraphNode*> ret;
while (!st.empty()) {
ret.push_back(st.top());
st.pop();
} return ret;
} private:
void topologicalSortUtil(DirectedGraphNode *node,
unordered_set<DirectedGraphNode*> &unique,
stack<DirectedGraphNode*> &st) {
// 处理 neighbors
for (const auto &nodePointer : node->neighbors) {
if (unique.count(nodePointer) == 0) {
unique.insert(nodePointer);
topologicalSortUtil(nodePointer, unique, st);
}
} // 处理完 neighbors ,自身入栈
st.push(node);
} void topologicalSort(vector<DirectedGraphNode*> graph,
unordered_set<DirectedGraphNode*> &unique,
stack<DirectedGraphNode*> &st) {
for (const auto &node : graph) {
if (unique.count(node) == 0) {
unique.insert(node);
topologicalSortUtil(node, unique, st);
}
}
}
};

[LintCode] 拓扑排序的更多相关文章

  1. BFS (1)算法模板 看是否需要分层 (2)拓扑排序——检测编译时的循环依赖 制定有依赖关系的任务的执行顺序 djkstra无非是将bfs模板中的deque修改为heapq

    BFS模板,记住这5个: (1)针对树的BFS 1.1 无需分层遍历 from collections import deque def levelOrderTree(root): if not ro ...

  2. 算法与数据结构(七) AOV网的拓扑排序

    今天博客的内容依然与图有关,今天博客的主题是关于拓扑排序的.拓扑排序是基于AOV网的,关于AOV网的概念,我想引用下方这句话来介绍: AOV网:在现代化管理中,人们常用有向图来描述和分析一项工程的计划 ...

  3. 有向无环图的应用—AOV网 和 拓扑排序

    有向无环图:无环的有向图,简称 DAG (Directed Acycline Graph) 图. 一个有向图的生成树是一个有向树,一个非连通有向图的若干强连通分量生成若干有向树,这些有向数形成生成森林 ...

  4. 【BZOJ-2938】病毒 Trie图 + 拓扑排序

    2938: [Poi2000]病毒 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 609  Solved: 318[Submit][Status][Di ...

  5. BZOJ1565 [NOI2009]植物大战僵尸(拓扑排序 + 最大权闭合子图)

    题目 Source http://www.lydsy.com/JudgeOnline/problem.php?id=1565 Description Input Output 仅包含一个整数,表示可以 ...

  6. 图——拓扑排序(uva10305)

    John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task i ...

  7. Java排序算法——拓扑排序

    package graph; import java.util.LinkedList; import java.util.Queue; import thinkinjava.net.mindview. ...

  8. poj 3687(拓扑排序)

    http://poj.org/problem?id=3687 题意:有一些球他们都有各自的重量,而且每个球的重量都不相同,现在,要给这些球贴标签.如果这些球没有限定条件说是哪个比哪个轻的话,那么默认的 ...

  9. 拓扑排序 - 并查集 - Rank of Tetris

    Description 自从Lele开发了Rating系统,他的Tetris事业更是如虎添翼,不久他遍把这个游戏推向了全球. 为了更好的符合那些爱好者的喜好,Lele又想了一个新点子:他将制作一个全球 ...

随机推荐

  1. swift 属性值变化

    如果创建了一个结构体的实例并将其赋值给一个常量,则无法修改该实例的任何属性,即使有属性被声明为变量也不行. 这种行为是由于结构体(struct)属于值类型.当值类型的实例被声明为常量的时候,它的所有属 ...

  2. Spring ApplicationContext(五)invokeBeanFactoryPostProcessors

    Spring ApplicationContext(六)BeanPostProcessor 产生回顾一下 ApplicationContext 初始化的几个步骤:第一步是刷新环境变量:第二步是刷新 b ...

  3. Python之线程与进程

    今天我们来了解一下Python的线程和进程的管理机制 首先,我们要了解下线程跟进程的概念: 线程(Thread)是操作系统能够进行运算调度的最小的单位,是一堆cpu的指令.他被包含在进程中,是进程中的 ...

  4. java通过接口扩展枚举

    package com.hra.riskprice; import com.hra.riskprice.SysEnum.Factor_Type; import com.hra.riskprice.po ...

  5. 【WebService】WebService之WSDL文档深入分析(三)

    WSDL概念 WSDL(网络服务描述语言,Web Services Description Language)是一门基于 XML 的语言,用于描述 Web Services 以及如何对它们进行访问. ...

  6. Syslog和Windows事件日志收集

    Syslog和Windows事件日志收集 EventLog Analyzer从分布式Windows设备收集事件日志,或从分布式Linux和UNIX设备.交换机和路由器(Cisco)收集syslog.事 ...

  7. Sprign中常用注解

    1.@Component 创建类对象,相当于配置<bean/> 2.@Service 与 @Component功能相同 2.1写在ServiceImpl类上 (建议在ServiceImpl ...

  8. 核心一:DI

    1.DI:中文名称:依赖注入 2.英文名称:(Dependency Injection) 3.DI是什么?? 3.1 DI和IoC是一样的 3.2 当一个类(A)中需要依赖另一类(B)对象时,把B赋值 ...

  9. 2018.11.14 uoj#34. 多项式乘法(fft)

    传送门 NOIpNOIpNOIp爆炸不能阻止我搞oioioi的决心 信息技术课进行一点康复训练. fftfftfft板题. 代码: #include<bits/stdc++.h> usin ...

  10. Java十进制数转二进制的方法

    使用Integer.toBinaryString(num) ,可以把十进制数转换成二进制 //十进制转换成二进制 Integer.toBinaryString(num); binary 二进制 Sys ...