#include <bits/stdc++.h>
using namespace std;
#define int long long
const int maxn = 5e3 + 5;
int a[maxn], dp[maxn], pos[maxn];
struct FenwickTree{
vector<int> tree;
void init(int n){
tree.assign(n + 2, 0);
}
void update(int v, int val) {
for (; v < tree.size(); v += v & (-v)) tree[v] += val;
}
int get(int v) {
int res = 0;
for (; v; v -= v & (-v)) res += tree[v];
return res;
}
} bit;
void solve(){
int n; cin >> n;
for(int i = 1; i <= n; i++){
int x; cin >> x;
pos[x] = i;
dp[i] = 1e9;
}
bit.init(n + 1);
dp[0] = 0;
for(int i = 0; i <= n - 1; i++){
int cost = 0;
for(int j = i + 1; j <= n; j++){
int cur = j - i - 1;
cost += pos[j] - (i + 1) - (cur - bit.get(pos[j]));
dp[j] = min(dp[j], dp[i] + cost);
bit.update(pos[j], 1);
}
bit.init(n + 1);
for(int j = 1; j <= n; j++) if(j > i && pos[j] < pos[i + 1]) pos[j]++;
}
cout << dp[n] << '\n';
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
solve();
}
# | 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... |