Original address This is my personal AC first topological sorting problem.
The title explains the outcome of several sets of matches. Infer the final ranking. According to test instructions this is an obvious topological ordering problem.
Attention
- Assuming there are multiple situations due to possible rankings, make sure that the numbers are small before.
- The data entered by the topic may have repeated edges
Topology sequencing first counts the degrees of each node.
Put the number of nodes with a degree of 0 in the queue (This problem is placed in the priority queue).
Then the loop:
- Take out the head node of the team, as the starting point of the edge.
- Then "Delete the edge attached to the point." The code is to reduce the degree of one node (i.e. the end point) of this side of the graph.
- Assuming that after minus one, the entry of the end point becomes 0. Then the number of the end points is entered in the queue .
- Infers whether the queue is empty. If not, then return to 1
Priority Queue class--priority_queue<t> with priority queues in C + + STL. The default priority queue is the greater the value, the higher the priority.
So for example priority_queue<int> Q.
The elements here are in descending order.
Let's say we need to overload in order to achieve ascending.
priority_queue<int,vector<int>,greater<int> > Q;
>> One interesting question is that I don't have a vector header file. But this declares a queue, but does not error.
It seems that I do not know the bottom of the STL is not deep.
Code
#include <iostream> #include <queue> #include <cstdio> #include <cstring>using namespace std; BOOL Map[501][501];int in[501];p riority_queue<int,vector<int>,greater<int> > Q;void topo (int n) { for (int i=1;i<=n;i++) {if (in[i]==0) Q.push (i); } int c=1; while (!q.empty ()) {int v=q.top (); Q.pop (); if (c!=n) {cout<<v<< ""; C + +; } else cout<<v<<endl; for (int i=1;i<=n;i++) {if (!map[v][i]) continue; in[i]--; if (!in[i]) Q.push (i); }}}int Main () {int n,m,i,j; while (cin>>n>>m) {int k=0; memset (map,0,sizeof map); memset (in,0,sizeof in); while (m--) {cin>>i>>j; if (Map[i][j]) continue; Map[i][j]=1; in[j]++; } Topo (n); }}
hdu1285 topology sort + Priority queue