[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 ...
随机推荐
- 怎样防止应用因获取IDFA被AppStore拒绝
由于Appstore禁止不使用广告而採集IDFA的app上架,友盟提供IDFA版和不含IDFA版两个SDK,两个SDK在数据上并没有差异.採集IDFA是为了防止今后由于苹果可能禁止眼下使用的openu ...
- 纯CSS弹出层,城市切换效果
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...
- laravel文件存储Storage
use Illuminate\Support\Facades\Storage; //建立目录 Storage::disk('public')->makeDirectory(date('Y-m') ...
- win 7 下vim的使用
1.gVim74.exe ftp://ftp.vim.org/pub/vim/pc/gvim74.exe 2.vimcdoc-1.9.0-setup.exe 中文说明文档 http://211.147 ...
- Unity编辑器下获取动画的根运动状态并修改
我最初想直接修改.anim文件 但通过后来得到的信息,其实根运动状态储存在FBX.meta文件里,转出的.anim文件虽然也有根运动的信息但是算是塌陷过的,无法进行开关操作. 这是我针对有根运动.an ...
- Jetty - Connector源码分析
1. 描述 基于Jetty-9.4.8.v20171121. Connector接受远程机器的连接和数据,允许应用向远程机器发送数据. 1.2 类图 从类图看出AbstractConnector继承C ...
- Atitit.vod 视频播放系统 影吧系统的架构图 架构体系 解决方案
Atitit.vod 视频播放系统 影吧系统的架构图 架构体系 解决方案 1. 运行平台:跨平台 android ios pc mobile 1.1. -------------前端 界面------ ...
- erlang supervisor中启动普通的进程
文字部分转自: http://1234n.com/?post/qou3eb supervisor的子进程 一开始使用supervisor的时候,我用的是init/1返回子进程规格列表的方式,并且所有子 ...
- datatables 相关文章
http://blog.csdn.net/zhu_xiao_yuan/article/details/51252300 datatables参数配置详解 http://blog.csdn.net/j ...
- QT界面 理解QStyle和QStyleOption以及QStyleFactory
QStyleOption类和QStyle类简介 QStyleOption类存储QStyle函数使用的参数.QStyleOption及其子类包含了QStyle函数绘制图形元素所需的所有信息. 由于性能原 ...