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 <iostream>
#include <vector>
#include <algorithm>
#include <bitset>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <ctime>
#include <queue>
using namespace std;
typedef long long ll;
typedef long double ld;
#define fastInp cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0);
const ll MOD = 1e9 + 7, MX2 = 1e6, SZ = 5030, INF = 1e9;
ll n;
vector<ll> vec;
ll dp[SZ];
ll invs[SZ][SZ];
signed main() {
fastInp;
cin >> n;
vec.resize(n);
for (auto& c : vec) cin >> c;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (vec[i] > vec[j]) {
invs[vec[j]][vec[i]]++;
}
}
}
for (int i = 1; i <= n; i++) dp[i] = INF;
for (int i = 1; i < SZ; i++) {
for (int l = 0; l < SZ; l++) {
ll r = i + l;
if (r >= SZ) continue;
invs[l][r] += invs[l][r - 1] + invs[l + 1][r] - invs[l + 1][r - 1];
}
}
/* for (int k = 1; k <= n; k++) {
ll l = (k);
ll cst = (invs[0][n] - invs[k + 1][n] - invs[0][k]) + (l * (l - 1) / 2 - invs[0][k]);
dp[k] = min(dp[k], dp[0] + cst);
}*/
for (int i = 1; i <= n; i++) {
ll k = 0, ind = 0;
for (int j = 0; j < n; j++) {
if (vec[j] == i) ind = j;
}
for (int j = 0; j < ind; j++) {
if (vec[j] > i) k++;
}
dp[i] = min(dp[i], dp[i - 1] + k);
for (int k = i + 1; k <= n; k++) {
ll l = (k - i + 1);
ll cst = (invs[i][n] - invs[k + 1][n] - invs[i][k]) + (l * (l - 1) / 2 - invs[i][k]);
dp[k] = min(dp[k], dp[i - 1] + cst);
if (dp[n] == 3) {
cout << "";
}
}
}
cout << dp[n];
return 0;
}
/*
9 12
1 2
4 2
5 8
4 6
6 9
2 9
8 7
8 3
7 1
9 4
3 5
3 4
3 4
2 1
2 3
3 1
1 3
*/
# | 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... |