poj 2367 Genealogical tree【拓扑排序基础题】

题意:给出一个数 n,代表有n个点,编号为1-n,接下来n行,每行若干个数字,读到0结束,以行号为起点,输入的数字为终点建一条有向边,求一种可能的拓扑排序。

View Code
#include<stdio.h>
#include<stack>
#include<string.h>
using namespace std;

const int MAXN = 100 + 10;

struct node
{
    int to;
    struct node *next;
};

int nE;
node Edge[MAXN * 2];
node *head[MAXN];
int count[MAXN];
int ans[MAXN];
stack<int> st;

void add_edge(int u, int v)
{
    node *e = Edge + nE++;
    e->to = v;
    e->next = head[u];
    head[u] = e;
}

int main()
{
    int n;
    while(scanf("%d", &n) != EOF) {
        nE = 0;
        memset(head, 0, sizeof(head));
        memset(count, 0, sizeof(count));

        for(int i = 1; i <= n; i++) {
            int v;
            while(1) {
                scanf("%d", &v);
                if( !v ) {
                    break;
                }
                add_edge(i, v);
                count[v]++;
            }
        }

        while( !st.empty() ) {
            st.pop();
        }

        for(int i = 1; i <= n; i++) {
            if(count[i] == 0) {
                st.push(i);
                count[i] = -1;
            }
        }

        for(int i = 0; !st.empty(); i++) {
            int k = st.top();
            st.pop();
            ans[i] = k;

            for(node *e = head[k]; e; e = e->next) {
                count[e->to]--;
            }

            for(int j = 1; j <= n; j++) {
                if( !count[j] ) {
                    st.push(j);
                    count[j] = -1;
                }
            }
        }

        for(int i = 0; i < n; i++) {
            printf("%d%c", ans[i], i == (n-1) ? '\n' : ' ');
        }
    }
    return 0;
}

 

posted @ 2012-07-26 12:45  小猴子、  阅读(261)  评论(0编辑  收藏  举报