[Algorithms] Topological Sort
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的更多相关文章
- 【拓扑排序】【线段树】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 ...
 - topological sort~~~~初学
		
今天讲了topological sort 问题: 判环:记录入队的点数,若<n则有环,可证: 算法:o(n):queue or stack,而不是o(n^2)枚举 #. 关系运算图(vijos ...
 - topological sort
		
A topological sortof a dag G is a linear ordering of all its vertices such that if G contains anedg ...
 - 拓扑排序(Topological Sort)
		
Graph 拓扑排序(Topological Sort) 假设一个应用场景:你用 C 编写了一个爬虫工具,其中有很多自定义的库:queue.c.queue.h.stack.c.stack.h.heap ...
 - 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-16 Topological Sort(25 分)
		
Write a program to find the topological order in a digraph. Format of functions: bool TopSort( LGrap ...
 - [MIT6.006] 14. Depth-First Search (DFS), Topological Sort 深度优先搜索,拓扑排序
		
一.深度优先搜索 它的定义是:递归探索图,必要时要回溯,同时避免重复. 关于深度优先搜索的伪代码如下: 左边DFS-Visit(V, Adj.s)是只实现visit所有连接某个特定点(例如s)的其他点 ...
 - Leetcode: Alien Dictionary && Summary: Topological Sort
		
There is a new alien language which uses the latin alphabet. However, the order among letters are un ...
 - [Algorithms] Radix Sort
		
Radix sort is another linear time sorting algorithm. It sorts (using another sorting subroutine) the ...
 
随机推荐
- 转 理解与分析ios应用的崩溃报告
			
理解与分析ios应用的崩溃报告 源网址: http://developer.apple.com/library/ios/#technotes/tn2151/_index.html 当一个应用程序崩溃时 ...
 - Swashbuckle一个webapi调试利器
			
开发weibapi通常会使用postman或者其他模拟http请求的工具去模拟请求.但是这些工具需要自己保存请求地址的url以及参数 每次我都是先查询wiki看参数. 看见同事再用Swashbuckl ...
 - mongodb - Replication Set搭建过程
			
1.创建目录 mkdir -p /mongodb/data/r1 mkdir -p /mongodb/data/r2 mkdir -p /mongodb/data/r3 mkdir -p /mongo ...
 - CSDN开源夏令营 百度数据可视化实践 ECharts(8)
			
(1)前言 首先谢谢林峰老师,继续接着第七篇提到的内容.CSS布局确实非常累,感觉不好看了就的调整,总的看起来的高大上嘛.好了废话不再多说.今天主要就先解说一个页面的内容,对于CSS布局后面讲会具体的 ...
 - docker运行环境安装-centos(一)
			
在这里我们使用的是docker的社区版Docker CE,针对的是未安装docker的新的主机,如果安装过docker的早期版本,先卸载它们及关联的依赖资源,安装的版本为docker 18.03. 1 ...
 - C++ - 派生类强制转换为基类
			
派生类强制转换为基类 本文地址: http://blog.csdn.net/caroline_wendy/article/details/24268821 在多态的使用时, 派生类的指针或引用能够转换 ...
 - Redis(三):windows下Redis的安装配置以及注意事项
			
一.下载windows版本的Redis 去官网找了很久,发现原来在官网上可以下载的windows版本的,现在官网以及没有下载地址,只能在github上下载,官网只提供linux版本的下载 官网下载地址 ...
 - iptables常用规则:屏蔽IP地址、禁用ping、协议设置、NAT与转发、负载平衡、自定义链
			
iptables常用规则:屏蔽IP地址.禁用ping.协议设置.NAT与转发.负载平衡.自定义链 时间 -- :: IT社区推荐资讯 原文 http://itindex.net/detail/4772 ...
 - ruby之各种概念
			
一.引言 刚开始接触ruby,遇到问题于是上网查资料,但是有时候却又看不懂,这很大一部分原因是我不知道一些关于ruby的概念名词是什么意思,所以看了别人的回答也理解不了. 二.各种名词 ruby:这个 ...
 - The Definitive Guide To Django 2 学习笔记(三) URLconfs 和松耦合
			
前面的例子体现了一个设计模式中的重要思想,松耦合. 不论我们是将/time/改成/current_time/,还是新建一个/another-time-page/同样指向views.py中的 curre ...