题目来源:https://www.nowcoder.com/question/next
题意
中文题意不再解释,,,,
思路
这道题有一个“题眼”,parent[i]的取值范围。
这个题眼可以省去深搜而直接用递推式的方式去计算树的最大深度(最大深度)。
其次,就是利用贪心。
分情况:
1.如果是L<=maxLen,那么就直接输出L;
2.如果是L>maxLen:
考虑最坏情况,除了最大深度所在的树链(以下用主链表示)之外,其他都在root上,那么肯定是考虑先游历除了主链之外的链(因为,主链是最长的,遍历主链并返回到root,是最浪费步数的),并留给主链maxLen的步数,遍历其他链需要其他链的二倍的步数(因为要返回到root)。
以上是贪心的思想。
由于可能L巨大,所以如果遍历的点的个数大于n,取n。
得:min(n,1+maxLen+(L-maxLen)/2)。
代码
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long LL;
int parent[60];
int dp[200];
int main()
{
int n,L;
scanf("%d%d",&n,&L);
for(int i = 0; i<n-1; i++)
{
scanf("%d",&parent[i]);
}
int mx = 0;
for(int i = 0; i<n-1; i++)
{
dp[i+1] = dp[parent[i]]+1;
mx = max(mx,dp[i+1]);
}
int d = min(L, mx);
printf("%d\n",min(n,1+d+(L-d)/2));
}