codeforces Codeforces Round #530 (Div. 2) 1099 D Sum in the tree

题目链接http://codeforces.com/contest/1099/problem/D

题意:一棵有 n 个结点的树,根为 1 ,每一个顶点 v 都有一个为整数的 a[v] 值,以及 v 点到根节点的路径上所有顶点 a[i] 的和s[v],现给出奇数层的 s[i],偶数层的未知,让你求所有节点 a[i] 和最小

思路:设父节点 u 有 子节点 v1,v2,v3,v4...,让 s[u] = min(v1,v2,v3,v4...),则 a[i] 的和可达到最小,利用 a[v] = s[v] - s[u],可求出所有 a[i] 的和。

AC代码

#include<bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define per(i,a,n) for (int i=a;i<n;i++)
#define rep(i,a,n) for (int i=n-1;i>=a;i--)
#define show(x) cout<<x<<endl;
#define showEnd(x)   cout<<x<<endl; return 0;
#define show_(x)    cout<<x<<" ";
#define showxy(x,y) cout<<x<<" "<<y<<endl;
typedef long long ll;
const int maxn = 100005;
const ll INF = 0x3f3f3f3f;
const int MOD = 998244353;

ll i,j,n,a[maxn]={INF},f[maxn],p[maxn],s[maxn],b[maxn],ans = 0,cnt = 0;

vector<ll> v[maxn];

int main()
{
    IO
    cin>>n;
    for(i = 1; i < n; i++)
    {
        cin>>p[i];
        v[p[i]].push_back(i+1);
    }
    for(i = 1; i <= n; i++) cin>>s[i];
    for(i = n; i >= 1; i--)
    {
        ll temp = INF;
        if(v[i].size() && s[i] == -1)
        {
            for(j = 0; j < v[i].size(); j++)
                temp = min(temp, s[v[i][j]]);
            s[i] = temp;
        }
        for(j = 0; j < v[i].size(); j++)
        {
            if(s[v[i][j]] != -1)
            {
                temp = s[v[i][j]] - s[i];
                if(temp < 0)
                {
                    showEnd(-1)
                }
                ans += temp;
            }
        }
    }
    show(ans + s[1]);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值