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;
    }
  • 相关阅读:
    vue04-动画、组件
    vue02—— 动画、组件、组件之间的数据通信
    webpack使用
    Promise
    css 尾巴
    js尾巴
    Python字符串格式转换
    CentOS 6.5下Redmine的安装配置
    gem Errno::ECONNRESET: Connection reset by peer
    MySQL几个重要的目录
  • 原文地址:https://www.cnblogs.com/tonix/p/5366376.html
Copyright © 2011-2022 走看看