Poj 2367 Genealogical tree(拓扑排序)

题目:火星人的血缘关系,简单拓扑排序。很久没用邻接表了,这里复习一下。

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[n]);
		}
	}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/AndyDai/p/4734091.html