# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1011025 | rythm_of_knight | Arranging Shoes (IOI19_shoes) | C++14 | 0 ms | 0 KiB |
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>
#define int long long
#define ll long long
using namespace std;
struct Fenwick{
vector<int> tr;
int sz;
Fenwick(int N){
tr.resize(N+1);
sz=N;
}
void add(ll i, ll x){
for (; i<=sz; i+=(-i&i)) tr[i]+=x;
}
ll get(ll i){
ll sum=0;
for (; i; i-=(i&-i)) sum+=tr[i];
return sum;
}
};
long long count_swaps(std::vector<int> s) {
int n = s.size(), x, ans = 0;
// sgt st;
// st.init(n);
Fenwick tr(n+2);
vector <set <int>> p(n + 1, set <int>()), m(n + 1, set <int>());
for (int i = 0; i < n; i++) {
x = s[i];
if (x > 0) {
if (!m[x].empty()) {
auto it = m[x].begin();
int l = *it + tr.get(*it+1), r = i;
ans += r - l - 1;
m[x].erase(it);
tr.add(l+1, 1);
tr.add(r+2, -1);
} else {
p[x].insert(i);
}
} else {
x = -x;
if (!p[x].empty()) {
auto it = p[x].begin();
int l = *it + tr.get(*it+1), r = i;
ans += r - l;
p[x].erase(it);
tr.add(l+1, 1);
tr.add(r+2, -1);
} else {
m[x].insert(i);
}
}
}
return ans;
}