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;
void calculate_prefix();
constexpr static int INF = 1e8;
constexpr static int MXSIZE = 5000;
int prefix[MXSIZE+1][MXSIZE+1], v[MXSIZE], dp[MXSIZE+1][MXSIZE+1], n, p[MXSIZE];
int get(int x1, int y1, int x2, int y2);
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> v[i];
v[i]--;
p[v[i]] = i;
}
for (int i = 0; i < n; i++)
prefix[i+1][v[i]+1] = 1;
calculate_prefix();
dp[0][0] = p[0];
for (int i = 1; i < n; i++)
{
dp[i][i] = INF;
for (int j = 0; j < i; j++)
dp[i][i] = min(dp[i][i], dp[i-1][j]);
dp[i][i] += get(0, i, p[i], n);
for (int j = 0; j < i; j++)
dp[i][j] = dp[i-1][j] - get(p[i], j, n, i) + get(0, j, p[i], n);
}
int best = INF;
for (int i = 0; i < n; i++)
best = min(best, dp[n-1][i]);
#ifdef DEBUGGING
for (int i = 0; i < n; i++)
for (int j = 0; j <= i; j++)
cout << (i+1) << " " << (j+1) << ": " << dp[i][j] << "\n";
#endif
cout << best <<"\n";
}
void calculate_prefix() // O(n^2)
{
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
prefix[i][j] += prefix[i][j-1] + prefix[i-1][j] - prefix[i-1][j-1];
}
int get(int x1, int y1, int x2, int y2) // O(1)
{
return prefix[x2][y2] - prefix[x2][y1] - prefix[x1][y2] + prefix[x1][y1];
}
# | 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... |