Stay Hungry,Stay Foolish!

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;
}

 

posted @ 2023-02-06 23:03  lightsong  阅读(13)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel