S5來襲4/11旗艦上市5檔高息股比定存強10倍輕忽小中風,當心變殘障黃國昌嗆周祝瑛 教室一...
2012-12-02 19:56:58 人氣(327) | 回應(0) | 推薦(0) | 收藏(0) 上一篇 | 下一篇

[UVA] 10672 - Marbles on a tree

0
收藏
0
推薦

Problem E: 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.

Sample input

 
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

Output for sample input

7
14
20

P. Rudnicki

如同中山大學的呂為萱所寫的描述去解題,她的構想其實就是對於這個點有多少彈珠會經過,這個的計算只需要看成子樹總共缺多少彈珠,又或者是多多少彈珠,這兩個值得大小就是其經過的次數。

#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace std;
struct ND {
    int totm;
    vector<int> son;
};
ND T[10001];
long long ans = 0;
int used[10001];
int sol(int nd) {
    used[nd] = 1;
    int cnt = 0;
    for(vector<int>::iterator it = T[nd].son.begin();
        it != T[nd].son.end(); it++) {
        if(used[*it] == 0) {
            cnt += sol(*it);
            T[nd].totm += T[*it].totm;
        }
    }
    ans += abs(T[nd].totm-cnt-1);
    return cnt+1;
}
int main() {
    int n, v, m, s, x;
    int i, j;
    while(scanf("%d", &n) == 1 && n) {
        for(i = 1; i <= n; i++)
            T[i].son.clear(), used[i] = 0;
        for(i = 1; i <= n; i++) {
            scanf("%d %d %d", &v, &m, &s);
            T[v].totm = m;
            while(s--) {
                scanf("%d", &x);
                T[v].son.push_back(x);
                T[x].son.push_back(v);
            }
        }
        ans = 0;
        sol(1);
        printf("%lld\n", ans);
    }
    return 0;
}


10672Marbles on a tree
台長:Morris
人氣(327) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][樹型DP] 11782 - Optimal Cut
此分類上一篇:[UVA][樹型DP] 10308 - Roads in the North

我要回應
是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入以下數字 (ex:123)

(有*為必填)
詳全文