首页 > 程序开发 > 软件开发 > 其他 >

ACM篇:POJ 2367 -- Genealogical Tree

2016-12-06

ACM篇:POJ 2367 -- Genealogical Tree。拓扑排序入门。 include include include include include using namespace std; const int MAX = 100; int n; int degree[MAX+1]; vector son[MAX+1]; queue father; void top

拓扑排序入门。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <queue>
using namespace std;

const int MAX = 100;

int n;
int degree[MAX+1];
vector<int> son[MAX+1];
queue<int> father;

void top_sort()
{
    for (int i = 1; i <= n; i++)
    {
        if (!degree[i])
        {
            father.push(i);
        }
    }

    int cnt = 0;
    while (++cnt <= n)
    {
        int top = father.front();
        father.pop();
        degree[top] = -1;
        int sz = son[top].size();
        for (int i = 0; i < sz; i++)
        {
            if (--degree[son[top][i]] == 0)
                father.push(son[top][i]);
        }
        printf("%d ", top); 
    }
}
int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        int temp;
        while (scanf("%d", &temp))
        {
            if (!temp) 
                break;
            else 
            {
                degree[temp]++;
                son[i].push_back(temp);
            }
        }
    }
    top_sort();
    return 0;
}
相关文章
最新文章
热点推荐