1436D - Bandit in a City(思维+二分+细节)

62 篇文章 2 订阅
30 篇文章 0 订阅

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值