Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "shoes.h"
- #include <algorithm>
- #include <vector>
- using namespace std;
- // Fenwick tree
- void update(vector<int> &fenwick, int index, int value) {
- while (index < (int)fenwick.size()) {
- fenwick[index] += value;
- index += index & -index;
- }
- }
- int getSum(const vector<int> &fenwick, int index) {
- int sum = 0;
- while (index) {
- sum += fenwick[index];
- index -= index & -index;
- }
- return sum;
- }
- // Reverse fenwick tree for suffix sums
- void updateR(vector<int> &fenwick, int index, int value) {
- update(fenwick, (int)fenwick.size()-index, value);
- }
- int getSumR(const vector<int> &fenwick, int index) {
- return getSum(fenwick, (int)fenwick.size()-index);
- }
- long long count_swaps(vector<int> s) {
- int n = (int)s.size() / 2;
- vector<vector<int>> nxt[2];
- nxt[0] = nxt[1] = vector<vector<int>>(1+n);
- for (int i = 2*n-1; i >= 0; --i) {
- if (s[i] < 0) nxt[0][-s[i]].push_back(i);
- else nxt[1][s[i]].push_back(i);
- }
- vector<int> fenwickMoved(1+2*n);
- vector<bool> paired(2*n);
- long long swaps = 0;
- for (int i = 0; i < 2*n; ++i) {
- if (paired[i]) continue;
- int v = abs(s[i]), side = s[i] > 0;
- int j = nxt[1-side][v].back();
- swaps += (j + getSumR(fenwickMoved, j+1)) - (i + getSumR(fenwickMoved, i+1));
- if (!side) --swaps; // do not need to swap with each other
- updateR(fenwickMoved, j+1, +1);
- paired[i] = true, paired[j] = true;
- nxt[0][v].pop_back(), nxt[1][v].pop_back();
- }
- return swaps;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement