题目链接
题目分析
输出任一拓扑排序序列即可!
解题思路
邻接表存储有向图,实现拓扑排序
AC程序(C++)
/**********************************
*@ID: 3stone
*@ACM: POJ-2367 Genealogical tree
*@Time: 18/9/10
*@IDE: VSCode + clang++
***********************************/
#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 110;
int N;
int cnt[maxn]; //入度
vector<int> Adj[maxn];// 邻接表
//拓扑排序
void topsort() {
queue<int> Q;
for(int i = 1; i <= N; i++) {
if(cnt[i] == 0)
Q.push(i);
}
int num = 0;
while(!Q.empty()) {
int v = Q.front();
Q.pop();
if(++num == N) printf("%d\n", v);
else printf("%d ", v);
for(int i = 0; i < Adj[v].size(); i++) {
if(--cnt[Adj[v][i]] == 0)
Q.push(Adj[v][i]);
}
}//while
}
int main() {
int v;
while(scanf("%d", &N) != EOF) {
fill(cnt, cnt + maxn, 0);
for(int i = 0; i < maxn; i++) Adj[i].clear();
for(int i = 1; i <= N; i++) { //输入孩子信息
scanf("%d", &v);
while(v != 0) {
cnt[v]++;
Adj[i].push_back(v);
scanf("%d", &v);
}
}
topsort();
}
return 0;
}