Escape (HDU4857 + Reverse Topological Sorting)

Topic link: http://acm.hdu.edu.cn/showproblem.php?pid=4857

The question is in Chinese, so I won't explain the meaning of the question. Click the link to see it yourself~ There are two conditions for sorting this question, one is according to the given sequence (that is, the input u, v, the highest priority) , one is the serial number from small to large (the next priority). In the forward direction, because these two conditions are not easy to maintain, I want to use reverse topological sorting to achieve it. First record the out-degree of each node, then use the priority queue to maintain the order (using the default sorting from large to small), and finally output in reverse.

The code is implemented as follows:

 1 #include <queue>
 2 #include <cstdio>
 3 #include <vector>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 const int maxn = 3e4 + 7;
 8 int t, n, m, u, v, rk;
 9 int InDeg[maxn], Rank[maxn];
10 vector<int> G[maxn];
11 
12 void topsort() {
13     priority_queue<int> q;
14     for(int i = 1; i <= n; i++) {
15         if(InDeg[i] == 0) q.push(i);
16     }
17     int x;
18     while(!q.empty()) {
19         x = q.top(), q.pop();
20         Rank[rk++] = x;
21         int t = G[x].size();
22         for(int i = 0; i < t; i++) {
23             if(--InDeg[G[x][i]] == 0) q.push(G[x][i]);
24         }
25     }
26 }
27 
28 int main() {
29     scanf("%d", &t);
30     while(t--) {
31         scanf("%d%d", &n, &m);
32         for(int i = 0; i <= n; i++) {
33             G[i].clear();
34         }
35         memset(InDeg, 0, sizeof(InDeg));
36         for(int  i = 0; i < m; i++) {
37             scanf("%d%d", &u, &v);
38             G[v].push_back(u);
39             InDeg[u]++;
40         }
41         rk = 0;
42         topsort();
43         for(int i = n - 1; i >= 0; i--) {
44             if(i != (n - 1)) {
45                 printf(" ");
46             }
47             printf("%d", Rank[i]);
48         }
49         printf("\n");
50     }
51     return 0;
52 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325651838&siteId=291194637