【牛客网】黑白树(树型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 提高组] 神经网络(拓扑排序)

猜你喜欢

转载自blog.csdn.net/IAMLSL/article/details/114242941