Alternative+Arborescence

Given a graph, we define "proper coloring" as coloring of the graph nodes in such way that no two adjacent nodes have the same color. If we map each color to a positive integer, we can calculate the sum of all colors assigned to the graph.

In this problem you will be given a tree (connected graph with no simple loops). Can you determine what the minimum color sum can be achieved when the tree is properly colored? (Image to the right shows a proper coloring of the second example tree with sum=11)

Input
The input file consists of several test cases. Each test case starts with n (1 ≤ n ≤ 10000), the number of nodes in the tree. Next n lines will be of the form "u: v1 v2 ... vk" where u is the root of a subtree and vi's are its children (0 ≤ u, vi ≤ n-1).

Every test case will be followed by a blank line. Input ends with a case n=0, which should not be processed.

Output
For each test case print the minimum sum of colors that can be achieved by some proper coloring of the tree.

Sample Input
2

0:

1: 0

8

0: 1 2 3

1: 4 5

2:

3: 6 7

4:

5:

6:

7:

0

Sample Output
3

11

Reference
[]

Source Code code format="java5" public class AlternativeArborecsence { public static void main(String[] args) { int[][] input = { {}, { 0 } }; System.out.println(getMinimumSum(getLevel(input)));

input = new int[][] { { 1, 2, 3 }, { 4, 5 }, {}, { 6, 7 }, {}, {}, {}, {}}; System.out.println(getMinimumSum(getLevel(input))); }

// 최소합을 구한다. public static int getMinimumSum(int[] level) { // 짝수 레벨의 개수 int even = 0; for (int i = 0; i < level.length; i++) { if (level[i] % 2 == 0) { even++; }       }

// 홀수 레벨의 개수 int odd = level.length - even;

// 최소합을 만들기 위해 적은 쪽에 2를 할당 if (even > odd) { return even + odd * 2; }       return even * 2 + odd; }

// 트리의 레벨을 구한다. public static int[] getLevel(int[][] tree) { int[] level = new int[tree.length];

for (int i = 0; i < tree.length; i++) { for (int j = 0; j < tree[i].length; j++) { level[tree[i][j]] = level[i] + 1; }       }

return level; } } code

Comment