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. Google两步验证安装使用方法

    http://www.williamlong.info/archives/2754.html

  2. IIS7如何部署asp.net网站 (asp.net mvc 5 , asp.net 4.5 , asp.net 4.0 都可以 )

      第一步:发布网站 右键asp.net web项目,选择发布, 然后新建配置文件名称并选择 "文件系统" 发布方法. 目标位置选择本地新建的文件夹如: IISWebSite 第二 ...

  3. ASP.NET MVC 简单的分页思想与实现

    首先我们通过VS创建一个空的基于Razor视图引擎的ASP.NET MVC3 Web应用程序,命名为JohnConnor.Web 对创建过程或Razor不太了解的看官,请移步 ASP.NET MVC ...

  4. Java 继承、多态与类的复用

    摘要: 本文结合Java的类的复用对面向对象两大特征继承和多态进行了全面的介绍. 首先,我们介绍了继承的实质和意义,并探讨了继承,组合和代理在类的复用方面的异同.紧接着,我们依据继承引入了多态.介绍了 ...

  5. unity5, UI Button "On Button Down"

    unity5自带的UI Button的Inspector面板中只有On Click事件,如果我们想让一个按钮响应On Button Down事件该怎么办呢?方法是: 点Add Component-&g ...

  6. MySQL加速查询速度的独门武器:查询缓存

    [导读] 与朋友或同事谈到MySQL查询缓存功能的时候,个人喜欢把查询缓存功能Query Cache比作荔枝, 是非常营养的东西,但是一次性吃太多了,就容易上火而流鼻血,虽然不是特别恰当的比喻,但是有 ...

  7. atitit.验证码识别step4--------图形二值化 灰度化

    atitit.验证码识别step4--------图形二值化 灰度化 1. 常见二值化的方法原理总结 1 1.1. 方法一:该方法非常简单,对RGB彩色图像灰度化以后,扫描图像的每个像素值,值小于12 ...

  8. EM5-PE6B

    1. vocabulay 1.1 scary adj.令人恐怖的 This is a scary thing. you can construct some extremely scary scena ...

  9. python之版本管理

    linux 环境下怎样对不同的python环境进行 方便的切换呢?update-alternatives工具能够非常方便的帮我们完成这个任务.而windows环境下可通过anaconda来完成. 1. ...

  10. 【问题记录】shiro logout UnknownSessionException

    问题描述:web项目中使用shiro做登录权限控制,当shiro执行logout后,直接返回一个jsp路径会抛出org.apache.shiro.session.UnknownSessionExcep ...