Serval and Rooted Tree
标签: 动态规划 树形DP 树形结构
题目描述
Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before.
As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a node v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all nodes for which v is the parent. A vertex is a leaf if it has no children.
The rooted tree Serval owns has n nodes, node 1 is the root. Serval will write some numbers into all nodes of the tree. However, there are some restrictions. Each of the nodes except leaves has an operation max or min written in it, indicating that the number in this node should be equal to the maximum or minimum of all the numbers in its sons, respectively.
Assume that there are k leaves in the tree. Serval wants to put integers 1,2,…,k to the k leaves (each number should be used exactly once). He loves large numbers, so he wants to maximize the number in the root. As his best friend, can you help him?
Input
The first line contains an integer n (2≤n≤3⋅105), the size of the tree.
The second line contains n integers, the i-th of them represents the operation in the node i. 0 represents min and 1 represents max. If the node is a leaf, there is still a number of 0 or 1, but you can ignore it.
The third line contains n−1 integers f2,f3,…,fn (1≤fi≤i−1), where fi represents the parent of the node i.
Output
Output one integer — the maximum possible number in the root of the tree.
Example
Input
6
1 0 1 1 0 1
1 2 2 2 2
Output
1
Input
5
1 0 1 0 1
1 1 1 1
Output
4
Input
8
1 0 0 1 0 1 1 0
1 1 2 2 3 3 3
Output
4
Input
9
1 1 0 0 1 0 1 0 1
1 1 2 2 3 3 4 4
Output
5
题解
可以发现,我们如果知道叶子结点的值以后,我们直接遍历下去就可以的得到答案了。但我们不能枚举每个节点选什么值对吧,于是来看这max和min操作,其实就是得到儿子节点最大或最小那个,递归下去,反映的就是得到叶子结点的某一排名。
于是我们设dp[i]表示i节点通过操作后能得到叶子结点的最大排名。
转移方程:
若为max:dp[i] = max(dp[e[i].to])
若为min:dp[i] = sum(dp[e[i].to])
最后ans = n - dp[1] + 1;
代码
#include<bits/stdc++.h>
#define N 300010
using namespace std;
int n, x, sum = 0, k = 0;
int a[N], f[N], head[N];
struct node{int to, next;}e[N * 2];
void add(int u, int v)
{
e[++ k].next = head[u]; e[k].to = v;
head[u] = k;
}
void dfs(int x)
{
if(!head[x]) {sum ++, f[x] = 1; return;}
for(int i = head[x]; i; i = e[i].next)
{
dfs(e[i].to);
if(a[x] == 0) f[x] += f[e[i].to];
else f[x] = !f[x] ? f[e[i].to] : min(f[x], f[e[i].to]);
}
//printf("%d %d", x, f[x]); system("pause");
}
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i ++)
scanf("%d", &a[i]);
for(int i = 2; i <= n; i ++)
scanf("%d", &x), add(x, i);
dfs(1);
printf("%d", sum - f[1] + 1);
return 0;
}
心得
这道题当时考场没做出来,主要是模型转换的思维不够,还是要多积累,多刷题。