2013
11-10

# Marbles on a tree

n boxes are placed on the vertices of a rooted tree, which are numbered from 1 to n, 1 <= n <= 10000. Each box is either empty or contains a number of marbles; the total number of marbles is n.

The task is to move the marbles such that each box contains exactly one marble. This is to be accomplished be a sequence of moves; each move consists of moving one marble to a box at an adjacent vertex. What is the minimum number of moves required to achieve the goal?

The input contains a number of cases. Each case starts with the number n followed by n lines. Each line contains at least three numbers which are: v the number of a vertex, followed by the number of marbles originally placed at vertex v followed by a number d which is the number of children of v, followed by d numbers giving the identities of the children of v.

The input is terminated by a case where n = 0 and this case should not be processed.

For each case in the input, output the smallest number of moves of marbles resulting in one marble at each vertex of the tree.

9
1 2 3 2 3 4
2 1 0
3 0 2 5 6
4 1 3 7 8 9
5 3 0
6 0 0
7 0 0
8 2 0
9 0 0
9
1 0 3 2 3 4
2 0 0
3 0 2 5 6
4 9 3 7 8 9
5 0 0
6 0 0
7 0 0
8 0 0
9 0 0
9
1 0 3 2 3 4
2 9 0
3 0 2 5 6
4 0 3 7 8 9
5 0 0
6 0 0
7 0 0
8 0 0
9 0 0
0


7
14
20


//* @author: ccQ.SuperSupper
import java.util.*;
import java.io.*;
class node{
int init_have;
int sum_have;
int nodes;
Vector son = new Vector();
}
public class Main {

static int N = 10000+100;
public static void main(String []args) throws Exception{

int n,i,j,ans,cnt,sons,root;
node Tree[] = new node[N];
for(i=0;i< N;++i) Tree[i] = new node();

//Scanner cin = new Scanner(new FileInputStream("input.txt"));//System.in);
Scanner cin = new Scanner(System.in);

while(cin.hasNext()){
n = cin.nextInt();
if(n==0) break;
for(i=0;i<=n;++i){
Tree[i].sum_have = -1;
Tree[i].son.clear();
Tree[i].nodes = 0;
}
for(i=0;i< n;++i){
cnt = cin.nextInt();
Tree[cnt].init_have = cin.nextInt();
sons = cin.nextInt();
for(j=0;j< sons;++j){
ans = cin.nextInt();
Tree[cnt].son.add(ans);
Tree[ans].sum_have = -2;
}
}
root = 1;
for(i=1;i<=n;++i) if(Tree[i].sum_have==-1)
root = i;
System.out.println(dfs(Tree,root));
}
}

public static int dfs(node Tree[],int root){

int i,j,k,ans=0;
Tree[root].sum_have = Tree[root].init_have;
Tree[root].nodes = 1;
for(i=0;i< Tree[root].son.size();++i){
k = (Integer)Tree[root].son.get(i);
if(Tree[k].sum_have< 0){
ans+=dfs(Tree,k);
Tree[root].sum_have+=Tree[k].sum_have;
Tree[root].nodes+=Tree[k].nodes;
ans+=abs(Tree[k].sum_have-Tree[k].nodes);
}
}
return ans;
}
public static int abs(int a){
return a<0?-a:a;
}
}

1. Good task for the group. Hold it up for every yeara??s winner. This is a excellent oppotunity for a lot more enhancement. Indeed, obtaining far better and much better is constantly the crucial. Just like my pal suggests on the truth about ab muscles, he just keeps obtaining much better.