Sample Output
1 2 3 4 5
思路:
注意此题不是保证字典序,而是要最小的尽量在前面。
反向建图,将大的优先级放前面,然后逆序输出。
首先反向建图+逆序输出为一个答案。
然后要保证最小的在最前面,因为是逆序输出,所以优先级要反过来。
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<queue> using namespace std; const int maxn = 1e5+5; vector<int> g[maxn]; int degree[maxn], ans[maxn], n, m; void topSort() { priority_queue<int, vector<int>, less<int> > pq; for(int i = 1; i <= n; i++) if(!degree[i]) pq.push(i); int flag = 0, p = 1; while(!pq.empty()) { int u = pq.top(); pq.pop(); ans[p++] = u; for(int i = 0; i < g[u].size(); i++) { int v = g[u][i]; degree[v]--; if(!degree[v]) pq.push(v); } } for(int i = p-1; i >= 1; i--) printf("%d%c", ans[i], i==1 ? '\n' : ' '); } int main(void) { int t; cin >> t; while(t--) { scanf("%d%d", &n, &m); memset(degree, 0, sizeof(degree)); for(int i = 1; i <= n; i++) g[i].clear(); while(m--) { int u, v; scanf("%d%d", &u, &v); g[v].push_back(u); degree[u]++; } topSort(); } return 0; }
