This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//雪花飄飄北風嘯嘯
//天地一片蒼茫
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>
using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;
#define ll long long
#define ii pair<ll,ll>
#define iii pair<ii,ll>
#define fi first
#define se second
#define endl '\n'
#define debug(x) cout << #x << " is " << x << endl;
#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))
#define all(x) (x).begin(),(x).end()
#define sz(x) (int)(x).size()
#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>
//change less to less_equal for non distinct pbds, but erase will bug
mt19937 rng(chrono::system_clock::now().time_since_epoch().count());
int n;
ll arr[5005];
ll memo[5005][5005][2];
ll dp(int l,int r,int flag){
//cerr<<l<<" "<<r<<" "<<flag<<endl;
if (memo[l][r][flag]!=-1) return memo[l][r][flag];
memo[l][r][flag]=1e18;
ll height;
if (flag==0) height=arr[l];
else height=arr[r];
if (r-l==2){
return memo[l][r][flag]=arr[r+l>>1]-height;
}
ll res=1e18;
if (arr[l]<arr[l+1] && arr[r-1]>arr[r]){
if (arr[l+1]<arr[r-1]) res=min(res,arr[l+1]-height+dp(l+1,r,0));
else res=min(res,arr[r-1]-height+dp(l,r-1,1));
}
if (arr[l]>arr[l+1] && arr[r-1]<arr[r]){
if (arr[l+1]>arr[r-1]) res=min(res,height-arr[l+1]+dp(l+1,r,0));
else res=min(res,height-arr[r-1]+dp(l,r-1,1));
}
if (flag==0){
if (arr[l]<arr[l+1] && arr[r-1]<arr[r]){
if (arr[l+1]<arr[r]) res=min(res,arr[l+1]-height+dp(l+1,r,0));
else res=min(res,arr[r-1]-height+dp(l,r,1));
}
if (arr[l]>arr[l+1] && arr[r-1]>arr[r]){
if (arr[l+1]>arr[r]) res=min(res,height-arr[l+1]+dp(l+1,r,0));
else res=min(res,height-arr[r-1]+dp(l,r,1));
}
}
if (flag==1){
if (arr[l]<arr[l+1] && arr[r-1]<arr[r]){
if (arr[l]<arr[r-1]) res=min(res,height-arr[r-1]+dp(l,r-1,1));
else res=min(res,height-arr[l+1]+dp(l,r,0));
}
if (arr[l]>arr[l+1] && arr[r-1]>arr[r]){
if (arr[l]>arr[r-1]) res=min(res,arr[r-1]-height+dp(l,r-1,1));
else res=min(res,arr[l+1]-height+dp(l,r,0));
}
}
return memo[l][r][flag]=res;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
memset(memo,-1,sizeof(memo));
cin>>n;
rep(x,0,n) cin>>arr[x];
cout<<dp(0,n-1,0);
}
Compilation message (stderr)
climbers.cpp: In function 'long long int dp(int, int, int)':
climbers.cpp:43:32: warning: suggest parentheses around '+' inside '>>' [-Wparentheses]
return memo[l][r][flag]=arr[r+l>>1]-height;
~^~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |