#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;
}