题解:P14272 [ROI 2014 Day1] 玩具自动售货机
Memorylocked · · 题解
看原题请戳这里
思路
一道简单的 DP。
首先看数据范围是
具体代码过程
- dfs
O(n) 查询节点v 的位置。 - 在 dfs 回溯的过程中加上硬币从当前节点移动到下一个节点所需的次数(如果该连边的宽度小于
ans ,直接输出-1 )。
时间复杂度
节点数量为
AC 代码
码风不太好
#include<bits/stdc++.h>
using namespace std;
const int N=1e5;
long long n,v,lson[N+2][2],rson[N+2][2],flag,ans;
void dp(long long now){
if(now==v){
flag=1,ans=1;
return ;
}
if(lson[now][0]){
dp(lson[now][0]);
if(flag){
if(lson[now][1]<ans){
cout<<"-1";
exit(0);
}
lson[now][1]-=ans;
if(lson[now][1]<rson[now][1])ans=ans+rson[now][1]-lson[now][1]-1;
return ;
}
}
if(rson[now][0]){
dp(rson[now][0]);
if(flag){
if(rson[now][1]<ans){
cout<<"-1";
exit(0);
}
rson[now][1]-=ans;
if(rson[now][1]<=lson[now][1])ans=ans+lson[now][1]-rson[now][1];
}
}
return ;
}
int main(){
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++)cin>>lson[i][0]>>lson[i][1]>>rson[i][0]>>rson[i][1];
cin>>v;
dp(1);
cout<<ans;
return ( 0 - 0 );
}