Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 4857
Train of Thought-priority queue + reverse topology + reverse output
If there are many restrictions on the first pop-up to the array, then pop up unrestricted (with the priority queue by sequence number from large to small), and finally output in reverse order.
# Include <cstdio> # include <queue> # include <vector> # include <cstring> using namespace STD; # define n 30001int N, in [N], num [N], CNT; vector <int> V [N]; priority_queue <int, vector <int>, less <int> q; // large root heap void Init () {CNT = 0; for (INT I = 0; I <= N; I ++) V [I]. clear (); memset (in, 0, sizeof (in); memset (Num, 0, sizeof (Num); While (! Q. empty () Q. pop () ;}void top_sort () {for (INT I = 1; I <= N; I ++) if (in [I] = 0) Q. push (I); While (! Q. empty () {int W = Q. top (); q. pop (); num [CNT ++] = W; For (INT I = 0; I <V [w]. size (); I ++) {in [V [w] [I] --; If (in [V [w] [I] = 0) Q. push (V [w] [I]) ;}} int main () {// freopen ("a.txt", "r", stdin); int T, m, x, Y; scanf ("% d", & T); While (t --) {Init (); scanf ("% d", & N, & M); For (INT I = 0; I <m; I ++) {scanf ("% d", & X, & Y ); V [Y]. push_back (x); in [x] ++;} top_sort (); printf ("% d", num [cnt-1]); // reverse output for (INT I = cnt-2; I> = 0; I --) printf ("% d", num [I]); printf ("\ n");} return 0 ;}
Hdu-4857 escape Topology Sorting