码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank "Favorite sequence"

时间:2016-04-08 06:38:54      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

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

HackerRank "Favorite sequence"

标签:

原文地址:http://www.cnblogs.com/tonix/p/5366376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!