D - Restricted Permutation
D - Restricted Permutation
https://atcoder.jp/contests/abc223/tasks/abc223_d
思路
https://zhuanlan.zhihu.com/p/135094687
利用拓扑排序方法, 先找入度为0的点,建立优先队列,包括:
2 和 3
从2 和 3 中选择 字典序 更小的 2, 对应优先队列top
从图中删除2以及其连线
得到新的入度为0的点 1,加入优先队列
从1和3中选择 字典序 更小的 1, 对应优先队列top
优先队列中还剩3,
弹出3, 加入4, 弹出4.
对于有环的图, 存在入度永远不为0的情况, 则判断不能满足条件。
Code
https://atcoder.jp/contests/abc223/submissions/38676367
int n, m; map<int, int> counter; vector<int> edges[200000+5]; int main() { cin >> n >> m; for(int i=0; i<m; i++){ int ai, bi; cin >> ai >> bi; edges[ai].push_back(bi); counter[bi]++; } vector<int> got; priority_queue<int, vector<int>, greater<int>> pq; for(int i=1; i<=n; i++){ if (counter[i] == 0){ pq.push(i); } } while(!pq.empty()){ int least = pq.top(); pq.pop(); got.push_back(least); vector<int>& nexts = edges[least]; for(auto it: nexts){ int nextv = it; counter[nextv]--; if(counter[nextv] == 0){ pq.push(nextv); } } } if (got.size() != n){ cout << -1 << endl; return 0; } for(int i=0; i<got.size(); i++){ cout << got[i] << " "; } return 0; }
出处:http://www.cnblogs.com/lightsong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。