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 "shoes.h"
#include <bits/stdc++.h>
#include <cstdio>
#include <cassert>
#define all(x) x.begin(),x.end()
#define lowbit(x) x&(-x)
using namespace std;
const int NMAX = 4e5+2;
vector<int> fenwick(NMAX);
inline void add(int k, int v){
if(k <= 0) return;
while(k < NMAX){
fenwick[k] += v;
k += lowbit(k);
}
}
inline int read(int k){
int sum = 0;
while(k > 0){
sum+=fenwick[k];
k -= lowbit(k);
}
return sum;
}
long long count_swaps(std::vector<int> s) {
int n = (int)s.size();
if(n <= 16){
vector<int> neg;
for(int i = 0; i < n; i++){
if(s[i] < 0){
neg.push_back(i);
}
}
const int MAX = 16;
bitset<MAX> mark;
int ans = INT32_MAX;
do{
mark.reset();
vector<int> ar(n);
int aux = 0;
for(int i = 0; i < n/2; i++){
ar[aux] = neg[i];
for(int j = 0; j < n; j++){
if(mark[j] == false and s[j] == -s[ar[aux]]){
ar[aux+1] = j;
mark[j] = true;
break;
}
}
aux += 2;
}
vector<int> pos(n), num(n);
for(int i = 0; i < n; i++) pos[i] = num[i] = i;
int swp = 0;
for(int i = 0; i < n; i++){
swp += abs(i-pos[ar[i]]);
if(pos[ar[i]] < i){
for(int j = pos[ar[i]]+1; j <= i; j++){
pos[ num[j] ]--;
}
pos[ ar[i] ] = i;
}
if(i < pos[ar[i]]){
for(int j = pos[ar[i]]-1; j >= i; j--){
pos[num[j]]++;
}
pos[ ar[i] ] = i;
}
for(int i = 0; i < n; i++) num[pos[i]] = i;
}
ans = min(ans,swp);
}while(next_permutation(all(neg)));
return ans;
}
else{
queue<int> neg, pos;
for(int i = 0; i < n; i++){
if(s[i] < 0) neg.push(i);
else pos.push(i);
}
vector<int> ar(n);
for(int i = 0; i < n-1; i+=2){
ar[i] = neg.front(); neg.pop();
ar[i+1] = pos.front(); pos.pop();
}
for(int i = 2; i <= n; i++) add(i,1);
/*cout << "this is the arr: \n";
for(int i = 0; i < n; i++) cout << ar[i] << " ";
cout << "\n";*/
int l = 0, r = n-1;
int swp = 0;
while(l < r){
int position = read(ar[l]+1);
//cout << "L: " << l << " num of the ar: " << ar[l] << " position: " << position << "\n";
swp += abs(position-l);
add(l+1,1);
add(position+1,-1);
l++;
position = read(ar[r]+1);
//cout << "R: " << r << " num of the ar: " << ar[r] << " position: " << position << "\n";
swp += abs(position-r);
add(r+2,1);
add(position+1,-1);
r--;
}
return swp;
}
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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |