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. 数据库表syscolumns 各个字段含义 select * from syscolumns where name='textA'

    每个数据库创建后都会有一些系统表用来存储该数据库的一些基本信息 每个表和视图中的每列在表中占一行,存储过程中的每个参数在表中也占一行.该表位于每个数据库中. 列名 数据类型 描述 name sysna ...

  2. Android_JarZip压缩和解压文件

        本文资料来自<android开发权威指南> AndroidSDK中提供了java.util.jar和java.util.zip包中的若干类和接口来完成. 压缩文件基本步骤: 1.创 ...

  3. springMVC中实现用户登录权限验证

    通过上网搜资料显示,使用filter和interceptor都可以实现.不过推荐使用interceptor. 下面就使用Interceptor实现用户登录权限验证功能. 拦截器需要实现Inceptor ...

  4. 实时Web的发展历史

    传统的Web是基于HTTP的请求/响应模型的:客户端请求一个新页面,服务器将内容发送到客户端,客户端再请求另外一个页面时又要重新发送请求.后来有人提出了AJAX,AJAX使得页面的体验更加“动态”,可 ...

  5. (2.0)Smali系列学习之Smali语法

    一.smali的包中信息 .class  public Lcom/aaaaa;.super  Lcom/bbbbb;.source "ccccc.java" 1.它是com.aaa ...

  6. makefile之call函数

    call函数是唯一一个可以创建定制化参数函数的引用函数. 支持对自定义函数的引用; 支持将一个变量定义为一个复杂的表达式,用call函数根据不同的参数对它进行展开来获取不同的结果; 函数语法: $(c ...

  7. JSP、servlet、SQL三者之间的数据传递

    JSP.servlet.SQL三者之间的数据传递 博客分类: web开发 JSPservletSQL数据库连接池web开发  前言: 最近一直在做WEB开发,现总结一下这一段时间的体会和感触. 切记, ...

  8. FileStream常用的属性和方法 (转)

    对流进行操作时要引用 using System.IO; 命名空间 FileStream常用的属性和方法: 属性: CanRead 判断当前流是否支持读取,返回bool值,True表示可以读取 CanW ...

  9. java性能监控工具:jmap命令详解

    .命令基本概述 Jmap是一个可以输出所有内存中对象的工具,甚至可以将VM 中的heap,以二进制输出成文本.打印出某个java进程(使用pid)内存内的,所有‘对象’的情况(如:产生那些对象,及其数 ...

  10. 真正解决 Android Studio无法启动,gradle下载不了 提示“building “ 项目名”gradle project info”(原创20131216)

    最近开始研究Android Studio 开发,但是在开始的时候,一直下载gradle,弄了四天,都没有成功,什么FQ,什么设置gradle路径,都没有解决,但是有一次在公司的电脑上很成功的更新了,完 ...