ACM篇:POJ 2367 -- Genealogical Tree

拓撲排序入門。

#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;
}
發佈了58 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章