Codeforces Round #530 (Div. 1) 1098A Sum in the tree
A. Sum in the tree
Mitya has a rooted tree with nn vertices indexed from 11 to nn, where the root has index 11. Each vertex vv initially had an integer number av≥0av≥0 written on it. For every vertex vv Mitya has computed svsv: the sum of all values written on the vertices on the path from vertex vv to the root, as well as hvhv — the depth of vertex vv, which denotes the number of vertices on the path from vertex vv to the root. Clearly, s1=a1s1=a1 and h1=1h1=1.
Then Mitya erased all numbers avav, and by accident he also erased all values svsv for vertices with even depth (vertices with even hvhv). Your task is to restore the values avav for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you’re required to find one which minimizes the total sum of values avav for all vertices in the tree.
Input
The first line contains one integer nn — the number of vertices in the tree (2≤n≤1052≤n≤105). The following line contains integers p2p2, p3p3, … pnpn, where pipi stands for the parent of vertex with index ii in the tree (1≤pi<i1≤pi<i). The last line contains integer values s1s1, s2s2, …, snsn (?1≤sv≤109?1≤sv≤109), where erased values are replaced by ?1?1.
Output
Output one integer — the minimum total sum of all values avav in the original tree, or ?1?1 if such tree does not exist.
Examples
input
5
1 1 1 1
1 -1 -1 -1 -1
output
1
input
5
1 2 3 1
1 -1 2 -1 -1
output
2
input
3
1 2
2 -1 1
output
-1
這道題時說有一顆樹,樹有N個節點,每個節點有一個值Vi,沿著根節點到I節點求和得到SUMi,前綴和,現在刪去vi,且刪去了偶數深度節點的sumi,vi>=0,sumi<=1e9.現是否存在一棵這樣的樹使得各點vi的和相加最小,不存在就是,存在子節點sumi小于父節點sumi使得子節點vi為負值。當為偶數節點時,他要被做差分,他也要與父節點做差分,如果他有子節點時,他們幾個構成貪心的機制,代價=∑(sum[子節點]-sum[當前節點])+sum[當前節點]-sum[父節點] 可知當子節點大于1的時候sum[當前]越大越好,最大的符合條件的sum[當前]是 sum【子節點】的最小值,當沒有子節點時,顯而易見等于父節點的sum【父節點】時代價最小,當只有一個子節點時,代價去sum【子】與sum【父】帶價相同,歸到第一類,可以寫代碼了。
#include<bits/stdc++.h>#define Swap(a,b) a^=b^=a^=b#define cini(n) scanf("%d",&n)#define cinl(n) scanf("%lld",&n)#define cinc(n) scanf("%c",&n)#define speed ios_base::sync_with_stdio(0); // 切不可用scnaf;#define Max(a,b) a>b?a:b#define Min(a,b) a<b?a:busing namespace std;typedef long long ll;const int INF=0x3f3f3f3f;const int maxn=1e5+10;int fa[maxn];ll sum[maxn];int main(){speedint n;ll ans=0;cin>>n;for(int i=2;i<=n;i++){cin>>fa[i];}for(int i=1;i<=n;i++){cin>>sum[i];if(sum[i]==-1) sum[i]=1e9+1;// sum[i]=sum[i]==-1?1e9+1:sum[i];}// for(int i=1;i<=n;i++) cout<<sum[i]<<' '<<endl;// cout<<endl;for(int i=2;i<=n;i++){sum[fa[i]]=Min(sum[fa[i]],sum[i]);}// for(int i=1;i<=n;i++) cout<<sum[i]<<' '<<endl;for(int i=2;i<=n;i++){int temp=sum[i]-sum[fa[i]];if(temp<0) return cout<<-1<<endl,0;if(sum[i]<=1e9) ans+=temp;}cout<<sum[1]+ans<<endl;} 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Codeforces Round #530 (Div. 1) 1098A Sum in the tree的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《卧龙:苍天陨落》将在 2 月 24 日
- 下一篇: 长城汽车:今年将在澳洲市场陆续上市坦克、