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 edge\degree 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 pop\push old\new 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;
}

转载于:https://www.cnblogs.com/tonix/p/5366376.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值