zoukankan      html  css  js  c++  java
  • HackerRank "Favorite sequence"

    Typical topological sorting problem .. why is it 'difficult'?

    #include <iostream>
    #include <string>
    #include <vector>
    #include <queue>
    using namespace std;
    
    #define MAX_CNT 1000001
    vector<long> outdeg(MAX_CNT);
    vector<long> inc[MAX_CNT];
    
    void add_edge(long a, long b)
    {
        outdeg[a]++;
        inc[b].push_back(a);
    }
    
    int main()
    {
        //  Get input and compose graph
        vector<long> ar(MAX_CNT), used(MAX_CNT);
        long n;  cin >> n;
        for (int i = 1; i <= n; i++)
        {
            long q;  cin >> q;
            for (int j = 1; j <= q; j++)
            {
                cin >> ar[j];
                used[ar[j]] = 1;
            }
            // setup edgedegree info
            for (int j = 2; j <= q; j++)
            {
                add_edge(ar[j], ar[j - 1]);
            }
        }
    
        // maintain a min-heap of all leaves
        priority_queue<long, vector<long>,greater<long>> leaves;
        for (int i = 1; i <= MAX_CNT; i++)
        {
            if (outdeg[i] == 0 && used[i] == 1)
                leaves.push(i);
        }
    
        // iteratively, we poppush old
    ew leaves
        vector<long> ans;
        while (leaves.size())
        {        
            long v = leaves.top();
            leaves.pop();
            ans.push_back(v);
            for (int i = 0; i<inc[v].size(); i++)
            {
                long id = inc[v][i];
                outdeg[id]--;
                if (!outdeg[id]) leaves.push(id);
            }
        }
    
        for (int i = 0; i<ans.size(); i++)
        {
            if (i)cout << " ";
            cout << ans[i];
        }
        cout << endl;
        return 0;
    }
  • 相关阅读:
    [剑指 Offer 11. 旋转数组的最小数字]
    进程描述符(PCB)
    [剑指 Offer 57. 和为s的两个数字]
    Linux netstat命令
    kafka2.3.X配置文件
    docker
    shell操作mysql数据库
    Linux文件查找之find命令
    sed 切割日志文件
    Linux文本处理之awk
  • 原文地址:https://www.cnblogs.com/tonix/p/5366376.html
Copyright © 2011-2022 走看看