POJ - 2367 - Genealogical tree (拓扑排序(水))

本文介绍了一道关于拓扑排序的经典模板题,通过详细解释题意和提供AC代码示例,帮助读者理解如何实现拓扑排序算法。适用于初学者巩固拓扑排序的知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sorce::Click here

Sample Input

5
0
4 5 1 0
1 0
5 3 0
3 0

Sample Output

2 4 5 3 1

题意

一个拓扑排序的模板题,注意下题目的输入即可。

题解

今天刚刚学了拓扑排序,多敲下模板熟悉一下。

                                                                                                                                                                                                                 

AC code

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <functional>
#include <algorithm>
#define _USE_MATH_DEFINES
using namespace std;
typedef long long ll;
const int MAXN = 1e3+5;
int n, m;
int p[MAXN][MAXN];
int vis[MAXN];
int b[MAXN];
void topsort()
{
    for(int i=1; i<=n; i++)//有n个点要输出,即循环n次。
    {
        for(int j=1; j<=n; j++)//题目要求小的编号在前,所以从1->n遍历
        {
            if(!vis[j])//当该点入度为0时,将该点输出。并将该点vis--(即将该点进行已经访问过的标记),同时删除与该点相连的边
            {
                vis[j]--;
                if(i==1) printf("%d",j);
                else printf(" %d",j);
                for(int k=1; k<=n; k++)
                {
                    if(p[j][k]) vis[k]--;
                }
                break;//(找到一个点后,即可break,进行下一次)
            }
        }
    }
    printf("\n");
}
int main()
{
    int x;
    cin>>n;
    memset(p,0,sizeof(p));
    memset(vis,0,sizeof(vis));
    for(int i=1; i<=n; i++)
    {
        while(scanf("%d",&x))
        {
            if(x==0) break;
            if(!p[i][x])
            {
                p[i][x] = 1;
                vis[x]++;
            }
        }
    }
    topsort();
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值