Codeforces Round #530 (Div. 2)

RANK :2252 题数 :3

补题:

D - Sum in the tree

思路:贪心 把权值放在祖先节点上 ,预处理 每个节点保存 他与他儿子中 权值最小值即可。

最后会有一些叶子节点依旧为 INF 权值按0算即可,然后其他的权值计算为 它 - 它父亲的。

注意判断时候会出现父亲比儿子大的这种非法情况。

#include<bits/stdc++.h>
using namespace std;
#define inf 0x7f7f7f7f
#define ll long long
#define maxn 123456
ll fa[maxn],n,s[maxn],ans;
int main()
{
    scanf("%lld",&n);
    for(int i=2; i<=n; i++)
        scanf("%lld",&fa[i]);
    for(int i=1; i<=n; i++)
    {
        scanf("%lld",&s[i]);
        if(s[i]==-1)s[i]=inf;
    }
    ans=s[1];
    for(int i=2; i<=n; i++)
        s[fa[i]]=min(s[fa[i]],s[i]);
    for(int i=2; i<=n; i++)
    {
        if(s[i]==inf)s[i]=0;
        else
        {
            ans+=s[i]-s[fa[i]];
            if(s[i]-s[fa[i]]<0)
            {
                printf("-1\n");
                return 0;
            }
        }
    }
    printf("%lld\n",ans);
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/SDUTNING/p/10234588.html