HDU 1285 determines the competition ranking (Topology Sorting template)
It is easy to understand the meaning of the question. The key is to see the following: the matching ranking may not be unique. At this time, the team with a small number must be in the front;
Idea: this is the classic application of topological sorting. You can use the queue to prioritize the queuing of small numbers.
Topological sorting:
Topological sorting is a sort of directed acyclic graph (DAG) vertices. It makes it possible for a directed path from u to v to meet the requirements of u in the sequence before v.
Therefore, our algorithm can be described as follows:1. Locate all vertices whose degree is 0 in the entire graph, and press these vertices into the queue (stack). 2. Extract A point from the queue (stack) and output it, delete the vertex and its edge and find the point it points to. If the point is an origin point (after deleting the point pointing to it), it is pushed to the queue (stack) 3. Repeat the 2 process until it is empty.
Note: If the degree is 0, there are no subnodes. If the value is 1, there is only one node. If the value is 2, there are two subnodes. Why do we need to make a point of 0 first? When you define a node with a degree of 0, it means that there is no parent node, that is, no one is in front of it!
So the basic AC code:
# Include
# Include
Using namespace std; int map [502] [502], flag [502], m, n, val [502]; void topsort () {int I, j, k = 1; for (I = 1; I <= n; I ++) // There are n points, so you need to find n times {for (j = 1; j <= n; j ++) {if (flag [j] = 0) // point where the cyclic search degree is 0 {flag [j] --; val [k ++] = j; for (int x = 1; x <= n; x ++) // Delete the if (map [j] [x]) flag [x] --; // set the degree to 0 break;} if (j> n) return ;}} int main () {int I, j; while (cin >>n> m) {memset (map, 0, sizeof (map )); memset (flag, 0, sizeof (flag); // The degree of initialization for all vertices is 0int a, B; for (I = 1; I <= m; I ++) {cin> a> B; if (! Map [a] [B]) {map [a] [B] = 1; flag [B] ++; // degree increase} topsort (); for (I = 1; I <= n; I ++) if (I! = N) cout <
Code after priority queue optimization:
# Include
# Include
# Include
# Include
# Define deusing namespace std; const int N = 510 + 10; vector
G [N]; // The adjacent table int du [N], val [N]; int n, m; void topsort () {int I; priority_queue
, Greater
> Q; // define a priority queue and a smaller number of priority queues for (I = 1; I <= n; I ++) if (! Du [I]) q. push (I); int cnt = 1; while (! Q. empty () {int u = q. top (); q. pop (); val [cnt ++] = u; for (I = 0; I