C++代码
一道朴实无华的拓扑排序题
#include<iostream>
#include<cstring>
using namespace std;
const int N = 110;
int e[N * 2], ne[N * 2], h[N], idx;
int d[N];
int q[N];
int n;
void add(int a, int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void topsort(){
int tt = -1, hh = 0;
for(int i = 1; i <= n; ++i)
if(!d[i])
q[++tt] = i;
while(hh <= tt){
int t = q[hh++];
for(int i = h[t]; i != -1; i = ne[i]){
int j = e[i];
d[j]--;
if(d[j] == 0) q[++tt] = j;
}
}
for(int i = 0; i < n; ++i) printf("%d ", q[i]);
}
int main(){
cin >> n;
memset(h, -1, sizeof h);
int x;
for(int i = 0; i < n; ++i)
while(cin >> x, x) add(i + 1, x), d[x]++;
topsort();
return 0;
}