Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 1e5+7;
- struct edge{
- int x;
- long long cost;
- edge(int _x=0,long long _c=0ll):x(_x),cost(_c){}
- void read(){
- scanf("%d %lld",&x,&cost);
- }
- };
- edge l[N],r[N];
- edge p[N];
- int main(){
- //freopen("input.txt","r",stdin);
- int n;
- cin>>n;
- for(int i=1;i<=n;++i){
- l[i].read();
- r[i].read();
- if(l[i].x!=0){
- p[l[i].x]=edge(i,l[i].cost);
- }
- if(r[i].x!=0){
- p[r[i].x]=edge(i,r[i].cost);
- }
- }
- int v;
- cin>>v;
- long long ans=0;
- while(true){
- if(p[v].x==0){
- break;
- }
- int ls=v;
- v=p[v].x;
- if(ans+1>p[ls].cost){
- cout<<-1<<endl;
- return 0;
- }
- if(ls==r[v].x){
- ans+=max(l[v].cost-(r[v].cost-ans)+1ll,0ll);
- }
- else{
- ans+=max(r[v].cost-(l[v].cost-ans),0ll);
- }
- }
- cout<<ans+1<<endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement