Topological sort is an important application of DFS in directed acyclic graphs (DAG). For each edge (u, v) from node u to node v in the graph, u must appear before v in the topological sort.

Topological sort has many interesting applications. One of them is job scheduling, in which you are assigned many jobs, each of the job has some prerequisite jobs, that means some jobs must be finished before you can move on to a particular job. If we express this dependency using a DAG (each job is represented as a node; if job u must be finished before job v, there is a directed edge from node u to node v), the topological sort of the graph will be a feasible schedule for the jobs.

The implementation of topogical sort is based on the previous graph representation and the DFS algorithms in this passage. I also implement a function read_digraph to input a directed graph manually. It is basically the same to the function read_graph in the above link. You may refer to it for the formatting style of the graph and more information.

The following graph is used to test the code.

The code is as follows.

 #include <iostream>
#include <vector>
#include <queue>
#include <unordered_set> using namespace std; struct GraphNode {
int label;
vector<GraphNode*> neighbors;
GraphNode(int _label) : label(_label) {}
}; vector<GraphNode*> read_digraph(void) {
int num_nodes, num_edges;
scanf("%d %d", &num_nodes, &num_edges);
vector<GraphNode*> graph(num_nodes);
for (int i = ; i < num_nodes; i++)
graph[i] = new GraphNode(i);
int node, neigh;
for (int i = ; i < num_edges; i++) {
scanf("%d %d", &node, &neigh);
graph[node] -> neighbors.push_back(graph[neigh]);
}
return graph;
} void topological(vector<GraphNode*>& graph, GraphNode* node, \
unordered_set<GraphNode*>& visited, vector<GraphNode*>& nodes) {
visited.insert(node);
for (GraphNode* neigh : node -> neighbors)
if (visited.find(neigh) == visited.end())
topological(graph, neigh, visited, nodes);
nodes.push_back(node);
} vector<GraphNode*> topological_sort(vector<GraphNode*>& graph) {
vector<GraphNode*> nodes;
unordered_set<GraphNode*> visited;
for (GraphNode* node : graph)
if (visited.find(node) == visited.end())
topological(graph, node, visited, nodes);
reverse(nodes.begin(), nodes.end());
return nodes;
} void graph_test(void) {
vector<GraphNode*> graph = read_digraph();
// Topological Sort
printf("Topological Sort:\n");
vector<GraphNode*> topo_sort = topological_sort(graph);
for (GraphNode* node : topo_sort)
printf("%d ", node -> label);
printf("\n");
} int main(void) {
graph_test();
system("pause");
return ;
}

The above graph is input as as follows:


The output is as follows:

Topological Sort:
        

Now if you reorder the nodes of the graph in the order of the topological sort, all the edges will be pointing from left to right, as shown in the graph below.

[Algorithms] Topological Sort的更多相关文章

  1. 【拓扑排序】【线段树】Gym - 101102K - Topological Sort

    Consider a directed graph G of N nodes and all edges (u→v) such that u < v. It is clear that this ...

  2. topological sort~~~~初学

    今天讲了topological sort 问题: 判环:记录入队的点数,若<n则有环,可证: 算法:o(n):queue or  stack,而不是o(n^2)枚举 #. 关系运算图(vijos ...

  3. topological sort

    A topological sortof a dag G  is a linear ordering of all its vertices such that if G contains anedg ...

  4. 拓扑排序(Topological Sort)

    Graph 拓扑排序(Topological Sort) 假设一个应用场景:你用 C 编写了一个爬虫工具,其中有很多自定义的库:queue.c.queue.h.stack.c.stack.h.heap ...

  5. Some facts about topological sort

    Definition: a topological sort of a DAG G is a sort such that for all edge (i,j) in G, i precedes j. ...

  6. 6-16 Topological Sort(25 分)

    Write a program to find the topological order in a digraph. Format of functions: bool TopSort( LGrap ...

  7. [MIT6.006] 14. Depth-First Search (DFS), Topological Sort 深度优先搜索,拓扑排序

    一.深度优先搜索 它的定义是:递归探索图,必要时要回溯,同时避免重复. 关于深度优先搜索的伪代码如下: 左边DFS-Visit(V, Adj.s)是只实现visit所有连接某个特定点(例如s)的其他点 ...

  8. Leetcode: Alien Dictionary && Summary: Topological Sort

    There is a new alien language which uses the latin alphabet. However, the order among letters are un ...

  9. [Algorithms] Radix Sort

    Radix sort is another linear time sorting algorithm. It sorts (using another sorting subroutine) the ...

随机推荐

  1. asp.net 抓取新闻

    前台页面: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w ...

  2. Android 4.4KitKat AudioTrack 流程分析

    Android Audio 系统的主要内容: AudioManager:这个主要是用来管理Audio系统的,需要考虑整个系统上声音的策略问题,例如来电话铃声,短信铃声等,主要是策略上的问题. Audi ...

  3. xjc编码

    本篇文章是对jaxb xjc编码的问题进行了详细的分析介绍,需要的朋友参考下   平时喜欢根据写一个xjc批处理命令,根据xsd批量生成java类,觉得很方便也很酷.但是有时候xsd生成的java类中 ...

  4. unity, List namespace

    如果要使用List,需要using System.Collections.Generic;

  5. atitit.提取zip rar文件列表 java php c# 的原理与设计

    atitit.java提取zip rar文件列表 1. 取zip rar文件的场景问题 1 1.1. 多重压缩的问题 1 1.2. 文件名编码的问题 1 1.3. 目录的判定 1 2. rar的解析 ...

  6. Vivado Logic Analyzer的进一步探讨

    本文基于Vivado 2014.2,代码基于文章http://blog.chinaaet.com/detail/37239中使用的代码. 这一篇仅讨论在综合后的Netlist中选择信号进行捕获的方法. ...

  7. [elk]es增删改查最佳实战

    PUT app01 GET app01/_settings GET _all/_settings PUT app01/_settings { "number_of_replicas" ...

  8. makefile之if函数

    #if 函数的语法是: #$(if <condition>,<then-part> ) #或 #$(if <condition>,<then-part> ...

  9. linux--jdk安装与配置

    此处以centos下jdkjdk1.8.0_161安装(此处为rpm安装事例)为例 1.java官网下载页找到对应版本的jdk下载链接地址 2.下载对应版本的rmp包到服务器,执行如下指令: wget ...

  10. 用docker搭建测试环境--docker的基本操作

    上一篇文章中最后执行了docker pull centos的指令,经过一段时间的等待,会从hub.docker.com上下载docker官方最新的centos的images,接下来熟悉一下docker ...