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 33 * Date: 2002-09-13
44 * Source: predates tinyKACTL
55 * 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 .
99 * Time: $O(|V|+|E|)$
1010 */
1111#pragma once
1212
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 ]++ ;
1916 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 ()) {
2319 int i = - q .front (); // top() for priority queue
24- idx[i] = nr++ ;
20+ ret . push_back ( i ) ;
2521 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 );
2824 }
29- return nr == n ;
25+ return ret ;
3026}
You can’t perform that action at this time.
0 commit comments