【牛客网】黑白树(树型dp)

题目描述:

在这里插入图片描述在这里插入图片描述

解题思路:

AC代码:

#include<bits/stdc++.h>
     using namespace std;
     const int maxn=1e5+100;
     struct edge{
     int u;
     int v;
     int next;
     }e[2*maxn];
     int cnt=0,head[2*maxn],vis[maxn],s[maxn],k[maxn],to[maxn];
     void Insert(int u,int v){
     cnt++;
     e[cnt].v=v;
     e[cnt].next=head[u];
     head[u]=cnt;
     }
     int Max(int x,int y){
     return x>y ? x : y;
     }
     int ans=0;
     void  treedp(int cur){
      vis[cur]=1;
      if(!to[cur]){
      s[cur]=k[cur];
      ans++;
      return;
      }
      for(int i=head[cur];i>=0;i=e[i].next){
      int v=e[i].v;
      if(!vis[v]){
      treedp(v);
      k[cur]=Max(k[cur],k[v]-1);
      s[cur]=Max(s[cur],s[v]-1);
      }
      }
     if(!s[cur]){
     ans++;
     s[cur]=k[cur];
     }
     }
     int main(){
     int n;
     cin>>n;
     memset(head,-1,sizeof(head));
     for(int i=2;i<=n;i++){
     int fa;
     cin>>fa;
     Insert(fa,i);
     Insert(i,fa);
      to[fa]++;
     }
     for(int i=1;i<=n;i++)
          cin>>k[i];
     treedp(1);
     cout<<ans<<endl;
     return 0;
      }



上一篇博客:【洛谷】P1038 [NOIP2003 提高组] 神经网络(拓扑排序)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值