Genealogical tree (拓扑排序)

题目:The system of Martians' blood relations is confusing enough. Actually, Martians bud when they want and where they want. They gather together in different groups, so that a Martian can have one parent as well as ten. Nobody will be surprised by a hundred of children. Martians have got used to this and their style of life seems to them natural.
And in the Planetary Council the confusing genealogical system leads to some embarrassment. There meet the worthiest of Martians, and therefore in order to offend nobody in all of the discussions it is used first to give the floor to the old Martians, than to the younger ones and only than to the most young childless assessors. However, the maintenance of this order really is not a trivial task. Not always Martian knows all of his parents (and there's nothing to tell about his grandparents!). But if by a mistake first speak a grandson and only than his young appearing great-grandfather, this is a real scandal.
Your task is to write a program, which would define once and for all, an order that would guarantee that every member of the Council takes the floor earlier than each of his descendants.

大意:给火星人按年龄排序输出,一个火星人可以有100个父母,也可以有一百个儿子。。。。(真能生)

思路:拓扑排序(这应该算是板子吧?吧吧吧),开一个数组存入度,再开vector容器存儿子,循环每次从队头取出入度为0的一个点,然后压入ans数组,把它指向的儿子入度-1,如果入度为0,加入队列。最后输出ans数组即可。

代码:

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int n;
vector<int>g[105];
vector<int>ans;
int in[105];
void tuopu()
{
	queue<int>que;
	for(int i=1;i<=n;i++)
	{
		if(in[i]==0) que.push(i);
	}
	while(que.size()){
		int u=que.front();
		que.pop();
		ans.push_back(u);
		for(int i=0;i<g[u].size();i++){
			int v=g[u][i];
			in[v]--;
			if(in[v]==0) que.push(v);
		}
	}
	for(int i=0;i<ans.size();i++) printf("%d ",ans[i]);
}
int main()
{
	ans.clear();
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		g[i].clear();
	}
	for(int i=1;i<=n;i++)
	{
		int a;
		for(int j=1;j<=n;j++){
			scanf("%d",&a);
			if(a!=0){
			g[i].push_back(a);
			in[a]++;
		   }
		   else break;
		}
	}
	tuopu();
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值