您的位置:首页 > 其它

Poj 2367 Genealogical tree(拓扑排序)

2014-03-15 14:58 302 查看
题目:火星人的血缘关系,简单拓扑排序。很久没用邻接表了,这里复习一下。

import java.util.Scanner;

class edge {
int val;
edge next;
}

public class Main {

static int n;
static int MAXV = 1001;
static edge head[] = new edge[MAXV];
static int in[];
static boolean vis[];

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){

n = sc.nextInt();
for (int i = 0; i <= n; i++) {
head[i] = new edge();
}
in = new int[MAXV];
vis = new boolean[MAXV];

for (int i = 1; i <= n; i++) {
int a;
while ((a = sc.nextInt()) != 0) {
edge t = new edge();
t.val = a;
t.next = head[i].next;
head[i].next = t;
in[a]++;
}
}
int[] ans=new int[n+1];
String s = "";
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (in[j] == 0 && !vis[j]) {

vis[j] = true;
s += j+" ";
ans[i]=j;
edge t = head[j].next;
while (t != null) {
in[t.val]--;
t = t.next;
}
break;
}
}
}
for(int i=1;i<n;i++){
System.out.print(ans[i]+" ");
}
System.out.println(ans
);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: