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 <set>
#include <cassert>
#include "shoes.h"
using namespace std;
struct Segtree{
vector<int> cache;
Segtree (int n){
cache.resize(4 * n);
}
int update(int l, int r, int i, int ui, int ux){
if(ui < l || r <= ui) return cache[i];
if (l + 1 == r) return cache[i] = ux;
int m = l + (r-l)/2;
return cache[i] = update(l, m, i*2+1, ui, ux) + update(m, r, i*2+2, ui, ux);
}
int query(int l, int r, int i, int ql, int qr){
if (qr <= l || r <= ql) return 0;
if (ql <= l && r <= qr) return cache[i];
int m = l + (r-l)/2;
return query(l, m, i*2+1, ql, qr) + query(m, r, i*2+2, ql, qr);
}
};
long long count_swaps(vector<int> S){
set<pair<int, int>> lefts, rights;
for (int ii = 0; ii < S.size(); ++ii) {
int i = S[ii];
if (i < 0) lefts.insert({-i, ii});
else rights.insert({i, ii});
}
int n = S.size();
Segtree segtree (n);
long long ans = 0;
vector<bool> free (n, true);
for (int i = 0; i < n; ++i) {
if (!free[i]) {
continue;
}
int left, right;
if (S[i] < 0) {
left = i;
right = rights.lower_bound({-S[i], 0})->second;
}
else {
right = i;
left = lefts.lower_bound({S[i], 0})->second;
}
int f1, f2;
lefts.erase({abs(S[i]), left});
rights.erase({abs(S[i]), right});
ans += f1 = left - segtree.query(0, n, 0, 0, left);
segtree.update(0, n, 0, left, 1);
ans += f2 = right - segtree.query(0, n, 0, 0, right);
assert(f1 == 0 || f2 == 0);
segtree.update(0, n, 0, right, 1);
free[left] = free[right] = false;
}
return ans;
}
/*
int main(){
cout << count_swaps({2, 2, 2, -2, -2, -2}) ;
}*/
Compilation message (stderr)
shoes.cpp: In function 'long long int count_swaps(std::vector<int>)':
shoes.cpp:31:25: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
31 | for (int ii = 0; ii < S.size(); ++ii) {
| ~~~^~~~~~~~~~
# | 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... |