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>
using namespace std;
const int MX = 5004;
int n;
int a[MX];
int cost[MX][MX];
int st[MX*4];
void upd(int l, int r, int id, int val, int v) {
if(l==r) {
st[v] = val;
return;
}
int mid = (l+r)/2;
if(id<=mid) upd(l, mid, id, val, v*2);
else upd(mid+1, r, id, val, v*2+1);
st[v] = st[v*2]+st[v*2+1];
}
int query(int l, int r, int L, int R, int v) {
if(l>=L && r<=R) return st[v];
if(l>R || r<L) return 0;
int mid = (l+r)/2;
return query(l, mid, L, R, v*2) + query(mid+1, r, L, R, v*2+1);
}
int dp[MX];
int solve(int i) {
if(i>n) return 0;
int &ret = dp[i];
if(ret!=-1) return ret;
ret = INT_MAX;
for(int j=i; j<=n; ++j) {
ret = min(ret, solve(j+1)+cost[i][j]);
}
return ret;
}
int alt[MX];
void PlayGround() {
cin>>n;
for(int i=1; i<=n; ++i) {
cin>>a[i];
alt[a[i]] = i;
}
int inv[n+1] = {};
for(int i=1; i<=n; ++i) {
for(int j=alt[i]-1; j>0; --j) if(a[j]>i) {
++inv[i];
}
}
for(int j=1; j<=n; ++j) {
for(int i=1; i<=n; ++i) {
upd(1, n, i, 0, 1);
}
for(int i=j; i>0; --i) {
cost[i][j] = inv[i] - query(1, n, 1, alt[i], 1) + query(1, n, alt[i], n, 1);
if(i!=j) cost[i][j] += cost[i+1][j];
upd(1, n, alt[i], 1, 1);
}
}
memset(dp, -1, sizeof dp);
cout<<solve(1)<<'\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
PlayGround();
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... |