標籤:can names 最大 深度 點距 mil ros style min
#include<bits/stdc++.h>
using namespace std;
int n,k;
vector<int>son[1000007];
int dp[1000007],depth[1000007],ans[1000007];//dp【i】表示離i最近的葉子節點距離i的深度,depth【i】表示以i為根,回到i所能到達的葉子節點的數量,ans【i】表示以i為根,能到達的葉子節點數目最大,即題意所需
void dfs(int now){
if(!son[now].size()){//本身為葉子結點
depth[now]=0;
dp[now]=1;
return;
}
int mn=1e9,mx=0;
for(const int&tmp:son[now]){//遍曆孩子結點
dfs(tmp);//繼續深搜
if(depth[tmp]<k)//小於k的話從now向下走可以走到孩子結點tmp所能觸及的葉子結點
dp[now]+=dp[tmp];//把孩子能碰到的葉子向上傳遞給父親
mx=max(mx,ans[tmp]-(depth[tmp]<k?dp[tmp]:0));//depth【tmp】<k時,dp【tmp】已經加到了dp【now】裡,把它減掉,mx留下的是最大的一次下去回不來所能碰到的葉子結點數
mn=min(mn,depth[tmp]+1);//now的深度為最小的孩子深度+1
}
depth[now]=mn;//mn只放最小的深度,那些子節點深度過大的都碰不到,只會碰一次符合題意的葉子結點(這次下去了就回不到祖先節點(這一次dfs的參數)了)
ans[now]=dp[now]+mx;//mx只能加一個所以放在迴圈之外
}
int main(){
scanf("%d%d",&n,&k);
int x;
for(int i=2;i<=n;i++){
scanf("%d",&x);
son[x].push_back(i);
}
dfs(1);
printf("%d\n",ans[1]);
return 0;
}
//有一種數組類比鏈表的遍曆結點方式,暫待瞭解
Educational Codeforces Round 52F(樹形DP,vector)