hiho1453 Rikka with Tree 01背包


#1453 : Rikka with Tree
Time Limit:10000ms
Case Time Limit:1000ms
Memory Limit:256MB

Description

As we know, Rikka is poor at math.Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. Here is one of them:

Yuta has a rooted tree with n nodes and the root is 1. Now he can do some operations on the tree. Each time he can choose a node i and cut down all the edges which connect i and its child.

Now Yuta wants to cut the tree into exactly k connected components, and he is interested in the minimal number of the operations to achieve this. So he wants Rikka to tell him the answer for each k ∈ [1, n].

It is too difficult for Rikka. Can you help her?
Input

The first line contains a number n (n ≤ 3000).

The second line contains n-1 numbers fi (1 ≤ fi ≤ i), the father of i+1.
Output

Print a line with n numbers, the ith number is the answer when k=i. If Yuta can't cut the tree into exactly k connected components, the answer will be -1.
Sample Input

    6
    1 2 1 1 2

Sample Output

    0 -1 1 1 -1 2

计算每个节点的儿子个数child[i]
不难发现 将i和所有儿子切开 就增加 child[i]个联通块
01背包一下即可


#include<iostream>
#include<stdio.h>
#include <algorithm>
#include<deque>
#include<set>
#include<map>;
using namespace std;
#define INF 1e+7

const int N = 3000 + 5;
int outDeg[N];

int d[N];

void slove(int n) {
    fill(d, d + n + 1, INF);
    d[1] = 0;
    for (int i = 1; i <= n; ++i) {
        int x = outDeg[i];
        for (int j = n; j >= 1; --j) {
            if (j + x <= n) {
                d[j + x] = min(d[j + x], d[j] + 1);
            }
        }
    }
    for (int i = 1; i <= n; ++i) {
        printf("%d ", d[i] <= n ? d[i] : -1);
    }
    putchar('\n');
}

int main() {
    //freopen("d:\\DATA_IN.txt", "r", stdin);
    int n, fa;
    scanf("%d", &n);
    for (int i = 0; i < n - 1; ++i) {
        scanf("%d", &fa);
        ++outDeg[fa];
    }
    slove(n);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值