Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1285
Because the input data must be parsed and the team with a small number must be in the front, use the priority queue to store the result set.
// The Key to topological sorting is to maintain a set of vertices whose input degree is 0. (Output only) # include <stdio. h> # include <string. h >#include <iostream >#include <queue> # define Max 510 using namespace STD; struct adj {int V; int last ;}; adj [Max * max]; int cnt_edge; // Number of edges int node [Max]; // Number of the last edge starting from X int in [Max]; // inbound int N, m; priority_queue <int, vector <int>, greater <int> q; // a team with a small number must be in the front, so the priority queue is used, sort void add_edge (int x, int y) in ascending order. // The queue simulation set {adj [cnt_edge]. last = node [X]; adj [cnt_edge]. V = y; // the end of the current edge. Node [x] = cnt_edge; // Number of the last edge starting from X cnt_edge ++;} // void clear () {cnt_edge = 0 for the creation of the adjacent table; // The number of edges starts from 0 for memset (in, 0, sizeof (in); // The initial input level is 0 for memset (node,-1, sizeof (node )); // initialize each vertex number as-1 while (! Q. Empty () Q. Pop ();} void top_sort () {vector <int> VEC; // Save the result set int now, next, J; while (! Q. empty () {now = Q. top (); Vec. push_back (now); // extracts a vertex from the set and puts the vertex into the result set. Q. pop (); For (j = node [now]; J! =-1; j = adj [J]. last) // traverses the adjacent table and traverses all the edges connected to it from the current vertex {next = adj [J]. v; in [next] --; // The input degree minus 1, indicating to remove this edge if (in [next] = 0) Q. push (next); // If the vertex's inbound degree is 0 after this edge is subtracted, then the vertex is also placed in the result set.} For (j = 0; j <Vec. size (); j ++) {// output result set if (j = 0) printf ("% d", VEC [J]); else printf ("% d", VEC [J]);} printf ("\ n");} int main () {// freopen ("B .txt ", "r", stdin); While (scanf ("% d", & N, & M) = 2) {clear (); int X, Y; while (M --) {scanf ("% d", & X, & Y); add_edge (x, y); in [y] ++; // X points to the edge of Y. The inbound degree of Y is added with 1} int I; for (I = 1; I <= N; I ++) if (in [I] = 0) // Add the vertex with the input degree of 0 to the set Q. push (I); top_sort ();} return 0 ;}
Hdu-1285 to determine the ranking