【POJ】[2367]Genealogical tree

文章字数:205

问题描述

Genealogical tree

问题分析

拓扑排序水题
给出n行
每行有以0结束的若干行数字,第i行的数字表示i排在这些数字前面
所以根据题意进行拓扑排序即可

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
int n,headcnt;
int cnt[120];
int topo[120];
int head[120];
struct node {
	int next;
	int to;
} a[120];
void toposort() {
	int top,t=0;
	for(int i=1; i<=n; i++) {
		for(int j=1; j<=n; j++) {
			if(cnt[j]==0) {
				top=j;
				break;
			}
		}
		topo[t++]=top;
		cnt[top]=-1;
		for(int j=head[top]; j!=-1; j=a[j].next) {
			cnt[a[j].to]--;
		}
	}
}
int main() {
	while(scanf("%d",&n)!=EOF) {
		memset(cnt,0,sizeof(cnt));
		memset(head,-1,sizeof(head));
		headcnt=0;
		for(int i=1; i<=n; i++) {
			int v;
			while(scanf("%d",&v),v) {
				a[headcnt].to=v;
				a[headcnt].next=head[i];
				head[i]=headcnt++;
				cnt[v]++;
			}
		}
		toposort();
		for(int i=0; i<n; i++)
			printf("%d%c",topo[i],i==n-1?'\n':' ');
	}
	return 0;
}

该内容采用 CC BY-NC-SA 4.0 许可协议。

如果对您有帮助或存在意见建议,欢迎在下方评论交流。

加载中...