A12266 | Up and Down the Tree
时间限制1s
内存限制256MB
通过 / 提交0/0
题目描述
You are given a <a>tree</a> with $n$ vertices; its root is vertex $1$ . 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 $v$ , then you make any of the following two possible moves:
- move down to any leaf in subtree of $v$ ;
- if vertex $v$ is a leaf, then move up to the parent no more than $k$ times. In other words, if $h(v)$ is the depth of vertex $v$ (the depth of the root is $0$ ), then you can move to vertex $to$ such that $to$ is an ancestor of $v$ and $h(v) - k \le h(to)$ .
Consider that root is not a leaf (even if its degree is $1$ ). Calculate the maximum number of different leaves you can visit during one sequence of moves.
- move down to any leaf in subtree of $v$ ;
- if vertex $v$ is a leaf, then move up to the parent no more than $k$ times. In other words, if $h(v)$ is the depth of vertex $v$ (the depth of the root is $0$ ), then you can move to vertex $to$ such that $to$ is an ancestor of $v$ and $h(v) - k \le h(to)$ .
Consider that root is not a leaf (even if its degree is $1$ ). Calculate the maximum number of different leaves you can visit during one sequence of moves.
输入格式
The first line contains two integers $n$ and $k$ ( $1 \le k < n \le 10^6$ ) — the number of vertices in the tree and the restriction on moving up, respectively.
The second line contains $n - 1$ integers $p_2, p_3, \dots, p_n$ , where $p_i$ is the parent of vertex $i$ .
It is guaranteed that the input represents a valid tree, rooted at $1$ .
The second line contains $n - 1$ integers $p_2, p_3, \dots, p_n$ , where $p_i$ is the parent of vertex $i$ .
It is guaranteed that the input represents a valid tree, rooted at $1$ .
输出格式
Print one integer — the maximum possible number of different leaves you can visit.
输入输出样例
输入 #1
7 1 1 1 3 3 4 4
输出 #1
4
输入 #2
8 2 1 1 2 3 4 5 5
输出 #2
2
The graph from the first example:
One of the optimal ways is the next one: $1 \rightarrow 2 \rightarrow 1 \rightarrow 5 \rightarrow 3 \rightarrow 7 \rightarrow 4 \rightarrow 6$ .
The graph from the second example:
One of the optimal ways is the next one: $1 \rightarrow 7 \rightarrow 5 \rightarrow 8$ . Note that there is no way to move from $6$ to $7$ or $8$ and vice versa.
One of the optimal ways is the next one: $1 \rightarrow 2 \rightarrow 1 \rightarrow 5 \rightarrow 3 \rightarrow 7 \rightarrow 4 \rightarrow 6$ .
The graph from the second example:
One of the optimal ways is the next one: $1 \rightarrow 7 \rightarrow 5 \rightarrow 8$ . Note that there is no way to move from $6$ to $7$ or $8$ and vice versa.
C++ 编辑器
输入
输出
可保存默认模板;新题优先使用已保存模板。
当前快捷键仅展示,暂不支持修改。
- 撤销
Ctrl / ⌘ + Z - 重做
Ctrl / ⌘ + Y - 查找
Ctrl / ⌘ + F - 全选
Ctrl / ⌘ + A - 复制
Ctrl / ⌘ + C - 剪切
Ctrl / ⌘ + X - 粘贴
Ctrl / ⌘ + V - 自动排版
工具栏排版按钮 - 草稿保存
编辑时自动保存到本机
历史
提交记录
状态说明时间源码
AI
作答助手
你好,我是作答助手。可以问思路、复杂度、样例含义或代码报错原因;不会直接给出完整 AC 代码。
确定要清空代码吗?
提交通过
评测结果:Accepted