https://codeforces.com/problemset/problem/1436/D
思路:
直接二分最后答案。
check:后序遍历从底下网上return。return 到该点是该点做多还能有的数量。累加好之后判是否超了。
注意sum的累加会炸longlong,同时128超时。
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+1000;
typedef int LL;
typedef unsigned long long ull;
inline LL read(){LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
vector<LL>g[maxn];
LL num[maxn];
bool flag=1;
ull dfs(LL u,LL fa,long long x){
if(!flag) return 0;
int son=0;
ull sum=0;
for(LL i=0;i<g[u].size();i++){
LL v=g[u][i];
if(v==fa) continue;
son++;
sum+=dfs(v,u,x);///当前这个点的人最多还能是sum,这么写sum会炸longlong,int128tle
}
if(son==0){///该节点是叶子
if(num[u]>x){
flag=0;return -1;
}
else{
return x-num[u];
}
}
else if(son!=0){
if(sum<num[u]){
flag=0;return 0;
}
else return sum-num[u];
}
}
inline bool check(long long mid){
flag=1;
dfs(1,-1,mid);
if(flag) return true;
else return false;
}
int main(void){
LL n;n=read();
for(LL i=2;i<=n;i++){
LL fa;cin>>fa;
g[fa].push_back(i);
}
for(LL i=1;i<=n;i++){
num[i]=read();
}
long long l=0;long long r=1e17;
while(l<r){
long long mid=(l+r)>>1;
if(check(mid)) r=mid;
else l=mid+1;
}
printf("%lld\n",l);
return 0;
}