设h为树的高度,sum[i]为深度大于i的点的个数
则$ans=max(i+lceilfrac{sum[i]}{k} ceil)$
注意到这是一条直线,于是斜率优化至$O(n)$
#include<cstdio> #define N 1000010 typedef long long ll; int n,m,i,x,g[N],nxt[N],v[N],ed,Q[N],c[N],sum[N],d,q[N],h=1,t,ans[N]; inline void read(int&a){char ch;while(!(((ch=getchar())>='0')&&(ch<='9')));a=ch-'0';while(((ch=getchar())>='0')&&(ch<='9'))a*=10,a+=ch-'0';} inline void add(int x,int y){v[++ed]=y;nxt[ed]=g[x];g[x]=ed;} void dfs(int x,int d){c[d++]++;for(int i=g[x];i;i=nxt[i])dfs(v[i],d);} inline int ceil(int a,int b){return a/b+(a%b>0);} int main(){ read(n),read(m); for(i=1;i<=m;i++)read(Q[i]); for(i=2;i<=n;i++)read(x),add(x,i); dfs(1,1); while(c[++d]); for(i=--d;~i;i--)sum[i]=sum[i+1]+c[i+1]; for(i=d;~i;q[++t]=i--)while(h<t&&(ll)(q[t-1]-q[t])*(sum[i]-sum[q[t]])>=(ll)(q[t]-i)*(sum[q[t]]-sum[q[t-1]]))t--; for(i=n;i;i--){ while(h<t&&(ll)i*(q[h]-q[h+1])<=sum[q[h+1]]-sum[q[h]])h++; ans[i]=q[h]+ceil(sum[q[h]],i); } for(i=1;i<=m;i++)printf(i<m?"%d ":"%d",Q[i]>n?d:ans[Q[i]]); return 0; }