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;
vector<int>p;
int const inf = 1e9;
int count_inversions(){
vector<int>idx(n+1);
bool valid = true;
for(int i = 1; i < n; i++){
if(p[i] < p[i-1]-1)
valid = false;
}
if(!valid)
return inf;
for(int i = 0; i < n; i++)
idx[p[i]] = i;
int inv = 0;
for(int i = 0; i < n; i++){
for(int j = i+1; j < n; j++){
if(idx[a[i]] > idx[a[j]])
inv++;
}
}
return inv;
}
void subtask1(){
p.resize(n);
iota(p.begin(), p.end(), 1);
int ans = inf;
do{
ans = min(ans, count_inversions());
}while(next_permutation(p.begin(), p.end()));
cout << ans << '\n';
}
void process_seq(){
}
void subtask2(){
p.resize(n);
iota(p.begin(), p.end(), 1);
int ans = inf;
for(int i = 0; i < (1<<(n)); i++){
vector<int>ss;
for(int j = 0; j < n; j++){
if(i & (1<<j)){
ss.push_back(j);
}
}
if(ss.size() == 0 || (ss.size() > 1 && ss[0] == 0))
continue;
reverse(p.begin(), p.begin()+ss[0]);
for(int j = 1; j < ss.size(); j++){
reverse(p.begin()+ss[j-1], p.begin()+ss[j]);
}
reverse(p.begin()+ss.back(), p.end());
ans = min(ans, count_inversions());
reverse(p.begin(), p.begin()+ss[0]);
for(int j = 1; j < ss.size(); j++){
reverse(p.begin()+ss[j-1], p.begin()+ss[j]);
}
reverse(p.begin()+ss.back(), p.end());
}
cout << ans << '\n';
}
int main(){
cin >> n;
a.resize(n);
for(int i = 0; i < n; i++)
cin >> a[i];
if(n <= 9){
subtask1();
}else if(n <= 20){
subtask2();
}
return 0;
}
Compilation message (stderr)
Main.cpp: In function 'void subtask2()':
Main.cpp:58:26: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
58 | for(int j = 1; j < ss.size(); j++){
| ~~^~~~~~~~~~~
Main.cpp:64:26: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
64 | for(int j = 1; j < ss.size(); j++){
| ~~^~~~~~~~~~~
# | 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... |