F. Up and Down the Tree
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given a tree with nn vertices; its root is vertex 11. Also there is a token, initially placed in the root. You can move the token to other vertices. Let's assume current vertex of token is vv, then you make any of the following two possible moves:
- move down to any leaf in subtree of vv;
- if vertex vv is a leaf, then move up to the parent no more than kk times. In other words, if h(v)h(v) is the depth of vertex vv (the depth of the root is 00), then you can move to vertex toto such that toto is an ancestor of vv and h(v)−k≤h(to)h(v)−k≤h(to).
Consider that root is not a leaf (even if its degree is 11). Calculate the maximum number of different leaves you can visit during one sequence of moves.
Input
The first line contains two integers nn and kk (1≤k<n≤1061≤k<n≤106) — the number of vertices in the tree and the restriction on moving up, respectively.
The second line contains n−1n−1 integers p2,p3,…,pnp2,p3,…,pn, where pipi is the parent of vertex ii.
It is guaranteed that the input represents a valid tree, rooted at 11.
Output
Print one integer — the maximum possible number of different leaves you can visit.
Examples
input
Copy
7 1 1 1 3 3 4 4
output
Copy
4
input
Copy
8 2 1 1 2 3 4 5 5
output
Copy
2
题目大意:有一颗树,假设当前处于节点x,若x不是叶结点,那么可以到达x所在子树的任意一个叶结点上,如果x是叶结点,那么可以到达x的所有距离不超过k的祖先节点上,问当起点为根节点时最多可以访问多少个叶结点。
dp,
dp[u][0]表示在节点u访问u的子树之后必须回来u节点的最大访问叶结点数
dp[u][1]表示在节点u访问u的子树之后停留在u的子树内部的最大访问叶结点数
其中dp[u][0]为所有可以返回到u的子树v的dp[v][0]之和
而dp[u][1] = max(dp[v][1] - dp[v][0]) + sigma(dp[v][0], v为u的儿子节点),即枚举最后停在哪个子树内部。
#include <cstdio>
#include <vector>
using namespace std;
const int N = 1e6 + 10;
vector<int> G[N];
int h[N], dp[N][2], n, k, x;
void dfs(int u, int fa) {
if (G[u].size() == 0) {
h[u] = k;
dp[u][0] = dp[u][1] = 1;
return;
}
h[u] = dp[u][0] = dp[u][1] = 0;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
dfs(v, u);
h[u] = max(h[v] - 1, h[u]);
if (h[v] > 0) dp[u][0] += dp[v][0];
}
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (h[v] > 0) dp[u][1] = max(dp[u][1], dp[u][0] - dp[v][0] + dp[v][1]);
else dp[u][1] = max(dp[u][1], dp[u][0] + dp[v][1]);
}
}
int main() {
scanf("%d%d", &n, &k);
for (int i = 2; i <= n; i++) {
scanf("%d", &x);
G[x].push_back(i);
}
dfs(1, -1);
printf("%d\n", dp[1][1]);
return 0;
}