考研数据结构练手二:拓扑排序。

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n, m, i, j;
    int* G;
    
    scanf("%d", &n);
    G = (int*)calloc((n + 1) * n + 1, sizeof(int));
    memset(G, 0, sizeof(G));
    
    while(1)
    {
        scanf("%d %d", &i, &j);
        if(i == 0 || j == 0) break;
        G[i * n + j] = 1;
        G[j]++;
    }
    
    for(m = 0; m < n; m++)
    {
        for(i = 1; i <= n; i++)
        {
            if(G[i] == -1)
                continue;
            if(G[i] == 0)
                break;
        }
        printf("%d\n", i);
        G[i] = -1;
        for(j = 1; j <= n; j++)
            if(G[i * n + j] == 1)
                                G[j]--;
    }
    free(G);
    return 0;
}