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>
#define all(i) (i).begin(), (i).end()
using namespace std;
#define debug(args...) cout << '[' << #args << "] is [", DEBUG(false, args), cout << ']' << endl
template<typename T>
void DEBUG(bool _sp, T i) {
if (_sp)
cout << ' ';
cout << i;
}
template<typename T, typename ...U>
void DEBUG(bool _sp, T i, U ...j) {
if (_sp)
cout << ' ';
cout << i;
DEBUG(true, j...);
}
template<typename T, typename U>
ostream& operator << (ostream &i, pair<T, U> j) {
i << '(' << j.first << ", " << j.second << ')';
}
template<typename T>
ostream& operator << (ostream &i, vector<T> j) {
i << '{' << j.size() << " :";
for (T _i : j)
i << ' ' << _i;
i << '}';
}
typedef long long ll;
typedef pair<int, int> pi;
typedef double dd;
const int inf = 0x3f3f3f3f, lg = 20;
const ll mod = 1e9 + 7, INF = 0x3f3f3f3f3f3f3f3f;
signed main() {
ios::sync_with_stdio(0), cin.tie(0);
const int N = 5005;
int n;
cin >> n;
int a[n], pos[n], pre[N][N];
for (int i = 0; i < n; ++i)
cin >> a[i], pos[--a[i]] = i;
for (int i = 0; i < n; ++i)
pre[0][i] = 0;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
pre[i + 1][j] = pre[i][j] + (a[i] <= j);
auto query = [&](int l, int r, int vl, int vr) {
if (l == r || vl == vr)
return 0;
int res = pre[r][vr - 1] - pre[l][vr - 1];
if (vl)
res -= pre[r][vl - 1] - pre[l][vl - 1];
return res;
};
int dp[n + 1];
dp[0] = dp[1] = 0;
for (int i = 2; i <= n; ++i) {
dp[i] = inf;
int tmp = 0, mn = n - i;
for (int j = 1; j <= i; ++j) {
int x = mn + j - 1, y = pos[x];
tmp -= query(y + 1, n, mn, x);
tmp += query(0, y, x + 1, n);
tmp += query(0, y, mn, x);
dp[i] = min(dp[i], dp[i - j] + tmp);
}
}
cout << dp[n];
}
/*
x+1 x+2 x/
x+1 x x+2
x+2 x+1 x
1 [N-1]
2 1 [N-2]
3 2 1 [N-3]
f(n) = min{
k,k-1,..,1, [n-k]
f(n-k) + <last n-k><first k> + <first i-1><i (<=k)>
} 1 <= k <= n
*/
Compilation message (stderr)
Main.cpp: In function 'std::ostream& operator<<(std::ostream&, std::pair<_T1, _T2>)':
Main.cpp:21:1: warning: no return statement in function returning non-void [-Wreturn-type]
21 | }
| ^
Main.cpp: In function 'std::ostream& operator<<(std::ostream&, std::vector<_Tp>)':
Main.cpp:28:1: warning: no return statement in function returning non-void [-Wreturn-type]
28 | }
| ^
# | 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... |