File tree Expand file tree Collapse file tree 1 file changed +12
-16
lines changed Expand file tree Collapse file tree 1 file changed +12
-16
lines changed Original file line number Diff line number Diff line change 3
3
* Date: 2002-09-13
4
4
* Source: predates tinyKACTL
5
5
* Description: Topological sorting. Given is an oriented graph.
6
- * Output is an ordering of vertices (array idx) , such that there are edges
7
- * only from left to right. The function returns false if there is a cycle in
8
- * the graph .
6
+ * Output is an ordering of vertices, such that there are edges only from left to right.
7
+ * If there are cycles, the returned list will have size smaller than $n$ -- nodes reachable
8
+ * from cycles will not be returned .
9
9
* Time: $O(|V|+|E|)$
10
10
*/
11
11
#pragma once
12
12
13
- template <class E , class I >
14
- bool topo_sort (const E &edges, I &idx, int n) {
15
- vi indeg (n);
16
- rep (i,0 ,n)
17
- trav (e, edges[i])
18
- indeg[e]++;
13
+ vi topo_sort (const vector < vi > & gr ) {
14
+ vi indeg (sz (gr )), ret ;
15
+ trav (li , gr ) trav (x , li ) indeg [x ]++ ;
19
16
queue < int > q ; // use priority queue for lexic. smallest ans.
20
- rep (i,0 ,n) if (indeg[i] == 0 ) q.push (-i);
21
- int nr = 0 ;
22
- while (q.size () > 0 ) {
17
+ rep (i ,0 ,sz (gr )) if (indeg [i ] == 0 ) q .push (- i );
18
+ while (!q .empty ()) {
23
19
int i = - q .front (); // top() for priority queue
24
- idx[i] = nr++ ;
20
+ ret . push_back ( i ) ;
25
21
q .pop ();
26
- trav (e, edges [i])
27
- if (--indeg[e ] == 0 ) q.push (-e );
22
+ trav (x , gr [i ])
23
+ if (-- indeg [x ] == 0 ) q .push (- x );
28
24
}
29
- return nr == n ;
25
+ return ret ;
30
26
}
You can’t perform that action at this time.
0 commit comments