CF--800--D

关键

解决掉孩子的前提下,能不能解决自己。
用一个w[i]数组记录一下孩子们的最大值,然后和l[i]和r[i]进行比较就可以了

代码

#include <bits/stdc++.h>
using namespace std;
#define int long long
const int M=2e5+5;
const int inf=1e9+1;

inline int read(){
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
    return x*f;
}

int h[M],ne[M],e[M],tot;
void add(int from,int to) {
    e[++tot]=to;  ne[tot]=h[from];  h[from]=tot;
}

int l[M],r[M],w[M],ans;
void dfs(int now) {
    for(int i=h[now];i;i=ne[i]) {
        int to=e[i];
        dfs(to);
        w[now]+=w[to];
    }
    if(w[now]>r[now])w[now]=r[now];
    else if(w[now]<l[now])w[now]=r[now],ans++;
}
//解决掉孩子的情况下能不能顺带解决自己
//可以的话就不需要加上
//脑子还是不行

signed main() {
    int TT=read();
    while(TT--) {
        int n=read();
        for(int i=1;i<=n;i++)w[i]=h[i]=0;
        tot=ans=0;
        for(int i=2;i<=n;i++) {
            int x=read();
            add(x,i);
        }
        for(int i=1;i<=n;i++)l[i]=read(),r[i]=read();
        dfs(1);
        cout<<ans<<endl;
    }
    return 0;
}
posted @ 2022-12-24 13:41  basicecho  阅读(38)  评论(0)    收藏  举报