D. Serval and Rooted Tree
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
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 vv is the last different from vv vertex on the path from the root to the vertex vv. Children of vertex vv are all nodes for which vv is the parent. A vertex is a leaf if it has no children.
The rooted tree Serval owns has nn nodes, node 11 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 maxmax or minmin 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 kk leaves in the tree. Serval wants to put integers 1,2,…,k1,2,…,k to the kk 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 nn (2≤n≤3⋅1052≤n≤3⋅105), the size of the tree.
The second line contains nn integers, the ii-th of them represents the operation in the node ii. 00 represents minmin and 11 represents maxmax. If the node is a leaf, there is still a number of 00 or 11, but you can ignore it.
The third line contains n−1n−1 integers f2,f3,…,fnf2,f3,…,fn (1≤fi≤i−11≤fi≤i−1), where fifi represents the parent of the node ii.
Output
Output one integer — the maximum possible number in the root of the tree.
Examples
input
Copy
6 1 0 1 1 0 1 1 2 2 2 2
output
Copy
1
input
Copy
5 1 0 1 0 1 1 1 1 1
output
Copy
4
input
Copy
8 1 0 0 1 0 1 1 0 1 1 2 2 3 3 3
output
Copy
4
input
Copy
9 1 1 0 0 1 0 1 0 1 1 1 2 2 3 3 4 4
output
Copy
5
有一棵树,1号节点为根节点,每个节点都有一个操作,取max或取min,取max表示该节点的值为他的儿子节点的值中最大的那个,同理取min,该树共有有k个叶子节点,现问如何将1-k这k个数分配到每个叶结点使得根节点值最大,每个数字只能使用一次。
树形dp,dp[i]表示节点i可以将以该节点为根的子树中所有叶节点中的第dp[i]大值排上来。
#include <cstdio>
#include <vector>
using namespace std;
const int N = 3e5 + 10;
const int INF = 1e9;
int n, op[N], dp[N], son;
vector<int> G[N];
void dfs(int x) {
dp[x] = 1;
if (G[x].size() == 0) {
son++;
return;
}
if (op[x]) dp[x] = INF;
else dp[x] = 0;
for (int i = 0; i < G[x].size(); i++) {
int y = G[x][i];
dfs(y);
if (op[x]) dp[x] = min(dp[x], dp[y]);
else dp[x] += dp[y];
}
}
int main() {
scanf("%d", &n);
int x;
son = 0;
for (int i = 1; i <= n; i++) scanf("%d", &op[i]);
for (int i = 2; i <= n; i++) {
scanf("%d", &x);
G[x].push_back(i);
}
dfs(1);
//for (int i = 1; i <= n; i++) printf("%d %d\n", i, dp[i]);
printf("%d\n", son - dp[1] + 1);
return 0;
}