族谱

输入一个数n,表示家谱中的总人数。

接下来n-1行,每行有2个整数x,y(1=<x<=n,1=<y<=n),表示x是y的父母。

输出n行,每行有一个整数表示第i个人有多少个直系后代。

输入:

1 2

1 3

2 4

输出:

1

0

0

dfs代码如下:

import java.util.LinkedList;
import java.util.Scanner;

public class L6 {

	static int n, x, y;
	static LinkedList<Integer>[] list = new LinkedList[10005];
	static boolean[] f = new boolean[10005];
	static int[] ans = new int[10005];

	public L6() {
		for (int i = 0; i < 10005; i++) {
			list[i] = new LinkedList<>();
		}
	}

	static int dfs(int u) {
		int ret = 0;
		for (int i = 0; i < list[u].size(); i++) {
			ret += dfs(list[u].get(i));
		}
		ans[u] = ret;
		return ret + 1;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		L6 l = new L6();
		for (int i = 0; i < n - 1; i++) {
			x = sc.nextInt();
			y = sc.nextInt();
			list[x].push(y);
			f[y] = true;
		}
		int u = 0;
		for (int i = 1; i <= n; i++) {
			if (!f[i]) {
				u = i;
				break;
			}
		}
		dfs(u);
		for (int i = 1; i <= n; i++) {
			System.out.println(ans[i]);
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_41921315/article/details/87943763
今日推荐