题目链接: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;
}