URAL 1022 Genealogical Tree

URAL_1022

    拓扑排序。

#include<stdio.h>

#include<string.h>

#define MAXD 110

#define MAXM 10010

int N, cnt, e, first[MAXD], next[MAXM], v[MAXM], topo[MAXD], vis[MAXD];

void add(int x, int y)

{

    v[e] = y;

    next[e] = first[x], first[x] = e ++;

}

void init()

{

    int i, j, k;

    memset(first, -1, sizeof(first));

    e = 0;

    for(i = 1; i <= N; i ++)

        for(;;)

        {

            scanf("%d", &k);

            if(k == 0)

                break;

            add(i, k);

        }

}

void dfs(int cur)

{

    int i;

    vis[cur] = 1;

    for(i = first[cur]; i != -1; i = next[i])

        if(!vis[v[i]])

            dfs(v[i]);

    topo[-- cnt] = cur;

}

void solve()

{

    int i, j, k;

    cnt = N;

    for(i = 1; i <= N; i ++)

        if(!vis[i])

            dfs(i);

    printf("%d", topo[0]);

    for(i = 1; i < N; i ++)

        printf(" %d", topo[i]);

    printf("\n");

}

int main()

{

    while(scanf("%d", &N) == 1)

    {

        init();

        solve();

    }

    return 0;

}

你可能感兴趣的:(tree)