剪开黑夜

In the twilight of every early morning

导航

拓扑排序

Posted on 2018-12-22 17:10  剪开黑夜  阅读(149)  评论(0编辑  收藏  举报

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <vector>
 5 #include <queue>
 6 #include <functional>
 7 using namespace std;
 8 #define maxn 100005
 9 
10 int n, a, indegree[maxn];    
11 vector<int> G[maxn];
12 
13 void TopoSort()
14 {
15     priority_queue<int, vector<int>, greater<int> >q;
16     for (int i = 1; i <= n; i++) 
17         if (indegree[i] == 0)q.push(i);
18     while (!q.empty()) {
19         int u = q.top();
20         q.pop();
21         printf("v%d ", u);
22         for (int i = 0; i < G[u].size(); i++) {
23             int v = G[u][i];
24             indegree[v]--;
25             if (indegree[v] == 0)
26                 q.push(v);
27         }
28     }
29 }
30 
31 int main()
32 {
33     int u, v;
34     cin >> n >> a;
35     for (int i = 0; i < a; i++) {
36         cin >> u >> v;
37         G[u].push_back(v);
38         indegree[v]++;
39     }
40     TopoSort();
41     printf("\n");
42     //system("pause");
43     return 0;
44 }