Advertisement
erek1e

IOI '19 - Shoes

Jun 29th, 2023
785
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include "shoes.h"
  2. #include <algorithm>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. // Fenwick tree
  8. void update(vector<int> &fenwick, int index, int value) {
  9.     while (index < (int)fenwick.size()) {
  10.         fenwick[index] += value;
  11.         index += index & -index;
  12.     }
  13. }
  14. int getSum(const vector<int> &fenwick, int index) {
  15.     int sum = 0;
  16.     while (index) {
  17.         sum += fenwick[index];
  18.         index -= index & -index;
  19.     }
  20.     return sum;
  21. }
  22. // Reverse fenwick tree for suffix sums
  23. void updateR(vector<int> &fenwick, int index, int value) {
  24.     update(fenwick, (int)fenwick.size()-index, value);
  25. }
  26. int getSumR(const vector<int> &fenwick, int index) {
  27.     return getSum(fenwick, (int)fenwick.size()-index);
  28. }
  29.  
  30. long long count_swaps(vector<int> s) {
  31.     int n = (int)s.size() / 2;
  32.     vector<vector<int>> nxt[2];
  33.     nxt[0] = nxt[1] = vector<vector<int>>(1+n);
  34.     for (int i = 2*n-1; i >= 0; --i) {
  35.         if (s[i] < 0) nxt[0][-s[i]].push_back(i);
  36.         else nxt[1][s[i]].push_back(i);
  37.     }
  38.  
  39.     vector<int> fenwickMoved(1+2*n);
  40.     vector<bool> paired(2*n);
  41.  
  42.     long long swaps = 0;
  43.     for (int i = 0; i < 2*n; ++i) {
  44.         if (paired[i]) continue;
  45.         int v = abs(s[i]), side = s[i] > 0;
  46.         int j = nxt[1-side][v].back();
  47.  
  48.         swaps += (j + getSumR(fenwickMoved, j+1)) - (i + getSumR(fenwickMoved, i+1));
  49.         if (!side) --swaps; // do not need to swap with each other
  50.         updateR(fenwickMoved, j+1, +1);
  51.    
  52.         paired[i] = true, paired[j] = true;
  53.         nxt[0][v].pop_back(), nxt[1][v].pop_back();
  54.     }
  55.     return swaps;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement