#include<bits/stdc++.h>
#define taskname "C"
using namespace std;
template<class T>void minimize(T& a, T b){
if(a > b){
a = b;
}
}
int n;
namespace sub1{
void solve(){
vector<int>a(n);
map<vector<int>, int>f;
for(int& x : a){
cin >> x;
}
f[a] = 1;
queue<vector<int>>q;
q.push(a);
while(!q.empty()){
a = q.front();
q.pop();
bool flag = true;
int init = f[a];
for(int i = 1; i < n; i++){
if(a[i - 1] > a[i] + 1){
flag = false;
}
swap(a[i - 1], a[i]);
if(f[a] == 0){
f[a] = init + 1;
q.push(a);
}
swap(a[i - 1], a[i]);
}
if(flag){
return void(cout << init - 1);
}
}
}
}
namespace sub2345{
const int lim = 5e3 + 5;
int dp[lim], pos[lim];
struct FenwickTree{
int bit[lim];
void reset(){
memset(bit, 0, sizeof(bit));
}
void update(int p, int x){
for(; p <= n; p += p & -p){
bit[p] += x;
}
}
int get(int p){
int ans = 0;
for(; p > 0; p -= p & -p){
ans += bit[p];
}
return ans;
}
};
FenwickTree up, down;
void solve(){
down.reset();
for(int i = 1; i <= n; i++){
int x;
cin >> x;
down.update(pos[x] = i, 1);
}
memset(dp, 0x0f, sizeof(dp));
dp[0] = 0;
for(int r = 1; r <= n; r++){
up.reset();
down.update(pos[r], -1);
int total = 0;
for(int l = r; l > 0; l--){
minimize(dp[r], dp[l - 1] + (total += l - pos[l] + down.get(pos[l]) + up.get(n - pos[l] + 1)));
up.update(n - pos[l] + 1, 1);
}
}
cout << dp[n];
}
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
if(fopen(taskname".inp", "r")){
freopen(taskname".inp", "r", stdin);
}
cin >> n;
if(n <= 9){
sub1::solve();
}
else{
sub2345::solve();
}
}
Compilation message (stderr)
Main.cpp: In function 'int main()':
Main.cpp:88:24: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
88 | freopen(taskname".inp", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
# | 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... |