LintCode-Topological Sorting

Given an directed graph, a topological order of the graph nodes is defined as follow:

  • For each directed edge A-->B in graph, A must before B in the order list.
  • The first node in the order can be any node in the graph with no nodes direct to it.

Find any topological order for the given graph.

Note

You can assume that there is at least one topological order in the graph.

Example

For graph as follow:

The topological order can be:

[0, 1, 2, 3, 4, 5]

or

[0, 2, 3, 1, 5, 4]

or

....

Challenge

Can you do it in both BFS and DFS?

Analysis:

A basica method is recording the pre nodes of every node, then find out a node without pre node in each iteration and delete this node from unvisited set.

DFS: use a recursive method, randomly pick up an unmakred node, before adding it into result list, recursively visite all its neighbors and add its neighbors into list first. In this way, we guarantee that all the nodes belong to some node‘s post nodes will be added to the result list first.

Solution 1:

 1 /**
 2  * Definition for Directed graph.
 3  * class DirectedGraphNode {
 4  *     int label;
 5  *     ArrayList<DirectedGraphNode> neighbors;
 6  *     DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
 7  * };
 8  */
 9 public class Solution {
10     /**
11      * @param graph: A list of Directed graph node
12      * @return: Any topological order for the given graph.
13      */
14     public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
15         ArrayList<DirectedGraphNode> res = new ArrayList<DirectedGraphNode>();
16         if (graph.size()==0) return res;
17
18         //Construct hash map.
19         Map<DirectedGraphNode, Set<DirectedGraphNode>> map = new HashMap<DirectedGraphNode, Set<DirectedGraphNode>>();
20         for (DirectedGraphNode node: graph){
21             Set<DirectedGraphNode> set = new HashSet<DirectedGraphNode>();
22             map.put(node,set);
23         }
24         for (DirectedGraphNode node : graph)
25             for (DirectedGraphNode temp: node.neighbors)
26                 map.get(temp).add(node);
27
28         //Construct topological order sequence.
29         int len = graph.size();
30         while (graph.size()>0) {
31             int index = 0;
32             while (index<graph.size()){
33                 DirectedGraphNode node = graph.get(index);
34                 if (map.get(node).size()==0){
35                     graph.remove(node);
36                     res.add(node);
37                     for (DirectedGraphNode temp: graph)
38                         if (map.get(temp).contains(node))
39                             map.get(temp).remove(node);
40                 } else index++;
41             }
42         }
43         return res;
44
45
46
47
48     }
49 }

Solution 2 (DFS):

 1 /**
 2  * Definition for Directed graph.
 3  * class DirectedGraphNode {
 4  *     int label;
 5  *     ArrayList<DirectedGraphNode> neighbors;
 6  *     DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
 7  * };
 8  */
 9 public class Solution {
10     /**
11      * @param graph: A list of Directed graph node
12      * @return: Any topological order for the given graph.
13      */
14     public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
15         ArrayList<DirectedGraphNode> res = new ArrayList<DirectedGraphNode>();
16         if (graph.size()==0) return res;
17         Map<DirectedGraphNode,Integer> status = new HashMap<DirectedGraphNode,Integer>();
18         for (DirectedGraphNode node: graph)
19             status.put(node,0);
20
21         while (hasUnsorted(status,graph)){
22             DirectedGraphNode node = null;
23             for (DirectedGraphNode temp : graph)
24                 if (status.get(temp)==0) node = temp;
25             search(status, graph, res, node);
26         }
27
28         return res;
29
30     }
31
32     public boolean hasUnsorted(Map<DirectedGraphNode,Integer> status, ArrayList<DirectedGraphNode> graph){
33         for (DirectedGraphNode node : graph)
34             if (status.get(node)==0) return true;
35
36         return false;
37     }
38
39     public void search(Map<DirectedGraphNode,Integer> status, ArrayList<DirectedGraphNode> graph, ArrayList<DirectedGraphNode> res, DirectedGraphNode node){
40         if (status.get(node)==1) System.out.println("It is not a DAG");
41         if (status.get(node)==2) return;
42         status.put(node,1);
43         for (DirectedGraphNode next : node.neighbors)
44             search(status,graph,res,next);
45         status.put(node,2);
46         res.add(0,node);
47     }
48
49 }
时间: 2024-10-14 07:03:52

LintCode-Topological Sorting的相关文章

Hdoj 5195 DZY Loves Topological Sorting 【拓扑】+【线段树】

DZY Loves Topological Sorting Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) Total Submission(s): 922 Accepted Submission(s): 269 Problem Description A topological sort or topological ordering of a directed graph i

hdu 5195 DZY Loves Topological Sorting 线段树+拓扑排序

DZY Loves Topological Sorting Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=5195 Description A topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for ev

BC DZY Loves Topological Sorting

DZY Loves Topological Sorting Accepts: 112 Submissions: 586 Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) 问题描述 一张有向图的拓扑序列是图中点的一个排列,满足对于图中的每条有向边(u→v) 从 u 到 v,都满足u在排列中出现在v之前. 现在,DZY有一张有向无环图(DAG).你要在最多删去k条边之后,求出字典序最大

hdu 5195 DZY Loves Topological Sorting BestCoder Round #35 1002 [ 拓扑排序 + 优先队列 || 线段树 ]

传送门 DZY Loves Topological Sorting Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 221    Accepted Submission(s): 52 Problem Description A topological sort or topological ordering of a directed

DZY Loves Topological Sorting (BC #35 hdu 5195 topsort+优先队列)

DZY Loves Topological Sorting Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others) Total Submission(s): 264    Accepted Submission(s): 63 Problem Description A topological sort or topological ordering of a directed gr

拓扑排序(Topological Sorting)

一.什么是拓扑排序 在图论中,拓扑排序(Topological Sorting)是一个有向无环图(DAG, Directed Acyclic Graph)的所有顶点的线性序列.且该序列必须满足下面两个条件: 每个顶点出现且只出现一次. 若存在一条从顶点 A 到顶点 B 的路径,那么在序列中顶点 A 出现在顶点 B 的前面. 有向无环图(DAG)才有拓扑排序,非DAG图没有拓扑排序一说. 例如,下面这个图: 它是一个 DAG 图,那么如何写出它的拓扑排序呢?这里说一种比较常用的方法: 从 DAG

hdu.5195.DZY Loves Topological Sorting(topo排序 &amp;&amp; 贪心)

DZY Loves Topological Sorting Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others) Total Submission(s): 866    Accepted Submission(s): 250 Problem Description A topological sort or topological ordering of a directed g

URAL(timus) 1280 Topological Sorting(模拟)

Topological Sorting Time limit: 1.0 secondMemory limit: 64 MB Michael wants to win the world championship in programming and decided to study N subjects (for convenience we will number these subjects from 1 to N). Michael has worked out a study plan

HDU 5195 - DZY Loves Topological Sorting

题意: 删去K条边,使拓扑排序后序列字典序最大 分析: 因为我们要求最后的拓扑序列字典序最大,所以一定要贪心地将标号越大的点越早入队.我们定义点i的入度为di. 假设当前还能删去k条边,那么我们一定会把当前还没入队的di≤k的最大的i找出来,把它的di条入边都删掉,然后加入拓扑序列. 删除的一定是小连大的边,因为大连小的边在拓扑序列生成的时候就去掉了 1 #include <iostream> 2 #include <cstdio> 3 #include <queue>

【HDU】5195-DZY Loves Topological Sorting(拓扑 + 线段树 + 贪心)

每次找出入度小于K的编号最大点. 找的时候用线段树找,找完之后将这个点出度链接的点的入度全部减一 简直爆炸... #include<cstdio> #include<vector> #include<cstring> #include<algorithm> using namespace std; #define lson (pos<<1) #define rson (pos<<1|1) const int maxn = 100005