[POJ] [2367] Genealogical tree

Problem Description

Loading...

Problem Analysis

A straightforward Topological Sort problem
n lines are given
each line contains several numbers ending with 0; the numbers on the i-th line mean i comes before these numbers
so just perform Topological Sort according to the problem statement

cpp
 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;
}
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...