poj 2367 Genealogical tree

题目链接:http://poj.org/problem?id=2367

题意:拓扑排序。

分析:题目中说必定存在一种排列满足,所以直接做,最后也不用判断是否全为0。(邻接表存起来,后者入度,然后度为零输出,入队列,队列中利用邻接表遍历。)

代码:

#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<cstdlib>
#include<string>
#include<vector>
#include<map>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
#define INF 0x3f3f3f3f
typedef long long ll;
#define Max(a,b) (a>b)?a:b
#define lowbit(x) x&(-x)
struct ss
{
    int a,next;
} e[100005];
int head[100005],hx;
int main()
{
    hx=0;
    memset(head,-1,sizeof(head));
    int n,du[105]= {0};
    scanf("%d",&n);int t;
    for(int i=1; i<=n; i++)
    {
        while(~scanf("%d",&t)&&t)
        {
            e[hx].a=t;
            e[hx].next=head[i];
            head[i]=hx++;
            du[t]++;
        }
    }
    queue<int>q;
    int flag=1;
    for(int i=1; i<=n; i++)
    {
        if(du[i]==0)
        {
            if(flag==1)
                flag=0;
            else
                printf(" ");
            printf("%d",i);
            q.push(i);
        }
    }
    while(!q.empty())
    {
        t=q.front();
//        printf("**%d**",t);
        q.pop();
        for(int i=head[t]; i!=-1; i=e[i].next)
        {
            t=e[i].a;
            du[t]--;
            if(du[t]==0)
            {            printf(" %d",t);
                q.push(t);
            }
        }
    }
    puts("");
}
View Code

 

转载于:https://www.cnblogs.com/wwdf/p/5781365.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值