[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 ...
随机推荐
- 悟道—位IT高管20年的职场心经(读书笔记一)
悟道--一位IT高管20年的职场心经 第一章 修炼! 修炼! 别跟我谈事业,先把工作做好. 别跟我说理想,先把饭碗端好: 志不可天天立.道必须日日修.没有实力,一切皆为妄谈. 修炼是硬道理. 1.1 ...
- 点滴积累【JS】---JS小功能(checkbox实现全选和全取消)
效果: 代码: <head runat="server"> <title></title> <script type="text ...
- Atitit.index manager api design 索引管理api设计
Atitit.index manager api design 索引管理api设计 1. kw 1 1.1. 索引类型 unique,normal,fulltxt 1 1.2. 聚集索引(cluste ...
- Swift中UIView类方法(animateWithDuration)的使用
需求:利用Swift语言实现OC语言中UIView类方法 [UIView animateWithDuration:0.5 animations:^{ bgView.alpha= 1; }]; 在Swi ...
- iOS网络访问之使用AFNetworking
AFNetworking是IOS上常用的第三方网络访问库,我们可以在github上下载它,同时github上有它详细的使用说明,最新的AFNetworing2.0与1.0有很大的变化,这里仅对2.0常 ...
- 在Windows下使用nmake+Makefile+编译ZThread库(附例子)
----------2015/01/09/23:21更新----------------------------------- 关于保留DEBUG信息的一个简单例子,见这篇随笔 ----------2 ...
- 解决eclipse偶尔无视breakpoint的行为
一般是如果你使用了T[]这样的参数列表,也就是generic array作为参数,你就算给函数打了断点,有时也会被eclipse无视 比如如下代码,你在调试main的时候,eclipse就会把doPa ...
- Linux源码安装过程中选项—prefix的作用
源码的安装一般由3个步骤组成:配置(configure).编译(make).安装(make install),具体的安装方法一般作者都会给出文档,这里主要讨论配置(configure).Configu ...
- npm太慢, 淘宝npm镜像使用方法[转]
淘宝 npm 地址: http://npm.taobao.org/ 如何使用 有很多方法来配置npm的registry地址,下面根据不同情境列出几种比较常用的方法.以淘宝npm镜像举例: 1.临时使用 ...
- hdu3667 Transportation 费用与流量平方成正比的最小流 拆边法+最小费用最大流
/** 题目:hdu3667 Transportation 拆边法+最小费用最大流 链接:http://acm.hdu.edu.cn/showproblem.php?pid=3667 题意:n个城市由 ...