跳到正文

个人记录

拓扑排序 家谱树

Rec°约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年4月21日
更新
2026年4月21日
篇幅
约 3 分钟

版本

  1. v1当前

- 题目描述

有个人的家族很大,辈分关系很混乱,请你帮整理一下这种关系。

给出每个人的孩子的信息。

输入一个序列,使得每个人的后辈都比那个人后列出。

- 输入

第一行一个整数(1<=N<=100),表示家族的人数。

接下来N行,第I行表示第I个人的儿子。

每行最后是0表示描述完毕。

输出

输出一个序列,使得每个人的后辈都比那个人后列出。

输出按照字典序输出

- 样例输入

5 0 4 5 1 0

1 0 5 3 0 3 0

- 样例输出

2 4 5 3 1


不多说,批注代码

C++
     #include <cstdio>
    #include <algorithm>
    #include <cstring>
    #include <queue>
    using namespace std;
    queue<int> q;//运用队列
    const int N=10000;
    const int M=1000000;
    int head[N],nex[M],to[M],ce;
    int in[N];//记录入读
    int n,m;
    void add(int u,int v){
        to[++ce]=v;nex[ce]=head[u];head[u]=ce;
        in[v]++;
    } //链式前向星 背下来 这里是单向边
    void topo(){//拓补排序
        for(int i=1;i<=n;i++) if(in[i]==0) q.push(i);//如果它是首边,入队列
        while(!q.empty()){//队列不为空开始跑拓补排序
            int u=q.front();//用u记录队头元素
            q.pop();//弹出对头 把值钱存入的i弹出
            printf("%d ",u);//弹出的时候同时输出
            for(int i=head[u];i;i=nex[i]){
                int v=to[i];
                in[v]--;
                if(in[v]==0) q.push(v);
            }
        }
    }
    int main(){
        scanf("%d",&n);
        for(int i=1;i<=n;i++){
            int j=1;
            while(j!=0) {
                scanf("%d",&j);
            if(j!=0) add(i,j);
        }
    }
        topo();
        return 0;
}
原文