#include<bits/stdc++.h>
using namespace std;
#define S second
#define F first
#define ll long long
//#define int long long
//#pragma GCC optimize("Ofast, unroll-loop")
//#pragma GCC target("avx,avx2")
#pragma GCC optimize("O3")
const int inf=0x3f3f3f3f;
const ll inff=0x3f3f3f3f3f3f3f3f;
//const int X=1000000007;
const int X=998244353;
int h[5005], cost1[5005][5005], cost2[5005][5005], dp[5005];
signed main(){
ios::sync_with_stdio(0), cin.tie(0);
memset(cost1,0,sizeof cost1);
memset(cost2,0,sizeof cost2);
int n; cin >> n;
for(int i=1 ; i<=n ; i++) cin >> h[i];
for(int i=1 ; i<n ; i++) for(int j=i+1 ; j<=n ; j++){
if(h[i]<h[j]){
cost2[1][h[j]]++;
cost2[h[i]+1][h[j]]--;
}
else{
cost1[1][h[i]]++;
cost1[h[j]+1][h[i]]--;
cost1[1][h[j]]++;
cost1[1][h[i]]--;
cost1[h[j]+1][h[j]]--;
cost1[h[j]+1][h[i]]++;
cost2[1][h[j]]++;
cost2[1][h[i]]--;
cost2[h[j]+1][h[j]]--;
cost2[h[j]+1][h[i]]++;
}
}
for(int i=1 ; i<=n ; i++) for(int j=1 ; j<=n ; j++)
cost1[i][j]+=cost1[i][j-1], cost2[i][j]+=cost2[i][j-1];
for(int i=1 ; i<=n ; i++) for(int j=1 ; j<=n ; j++)
cost1[i][j]+=cost1[i-1][j], cost2[i][j]+=cost2[i-1][j];
for(int i=1 ; i<=n ; i++) for(int j=i ; j<=n ; j++){
//cout << "cost1[" << i << "][" << j << "]=" << cost1[i][j] << '\n';
//cout << "cost2[" << i << "][" << j << "]=" << cost2[i][j] << '\n';
}
dp[1]=min(cost1[1][1],cost2[1][1]);
for(int i=2 ; i<=n ; i++){
dp[i]=inf;
for(int j=0 ; j<i ; j++) dp[i]=min(dp[i],dp[j]+min(cost1[j+1][i],cost2[j+1][i]));
//cout << "dp[" << i << "]=" << dp[i] << '\n';
}
cout << dp[n] << '\n';
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |