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 <numeric>
#include <queue>
using namespace std;
int n;
vector<int>a, idx;
vector<int>p;
int const inf = 1e9;
vector<int>dp;
vector<vector<int>>dpcost;
vector<vector<int>>left_num, right_num;
void precalc_cost(){
left_num.resize(n+1);
right_num.resize(n+1);
for(int i = 1; i <= n; i++){
for(int j = i+1; j <=n; j++){
left_num[a[j]].push_back(a[i]);
}
}
for(int i = n; i >= 1; i--){
for(int j = i-1; j >= 1; j--){
right_num[a[j]].push_back(a[i]);
}
}
for(int i = 1; i <= n; i++){
sort(left_num[i].begin(), left_num[i].end());
sort(right_num[i].begin(), right_num[i].end());
}
}
int query(vector<int> &v, int l, int r){
if(l > r)
return 0;
//numbers less than or equal to r
int num_r = lower_bound(v.begin(), v.end(), r+1)-v.begin();
//numbers less than l
int num_l = lower_bound(v.begin(), v.end(),l)-v.begin();
return num_r-num_l;
}
int query_left(int num, int l, int r){
return query(left_num[num], l, r);
}
int query_right(int num, int l, int r){
return query(right_num[num], l, r);
}
int cost(int pos, int val){
if(dpcost[pos][val] != -1)
return dpcost[pos][val];
//cout << "cost(" << pos << ',' << val << ")\n";
iota(p.begin(), p.end(), 0);
reverse(p.begin()+pos, p.begin()+val+1);
int inv = 0;
for(int i = pos; i <= val; i++){
if(i == pos){
inv += query_left(i, val+1, n);
inv += query_right(i, i+1, val);
}else if(i == val){
//inv += query_left(i, pos, i-1);
inv += query_left(i, val+1, n);
}else{
//inv += query_left(i, pos, i-1);
inv += query_left(i, val+1, n);
inv += query_right(i, i+1, val);
//inv += query_right(i, 1, pos-1);
}
}
int inv2 = 0;
for(int i = pos; i <= val; i++){
for(int j = i+1; j <= n; j++){
if((p[i] < p[j] && idx[i] > idx[j]) ||
(p[i] > p[j] && idx[i] < idx[j]))
inv2++;
}
}
//cout << inv << ' ' << inv2 << endl;
return dpcost[pos][val] = inv;
}
int solve(int k){
if(k > n)
return 0;
if(dp[k] != -1)
return dp[k];
//cout << "solve(" << k <<")" << endl;
int ans = inf;
for(int i = k; i <= n; i++){
ans = min(ans, cost(k, i) + solve(i+1));
}
return dp[k] = ans;
}
int main(){
cin >> n;
a.resize(n+1);
p.resize(n+1);
idx.resize(n+1);
dp.resize(n+1, -1);
dpcost.resize(n+1, vector<int>(n+1, -1));
for(int i = 1; i <= n; i++){
cin >> a[i];
idx[a[i]] = i;
}
precalc_cost();
cout << solve(1) << '\n';
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... |