Advertisement
Josif_tepe

Untitled

Apr 13th, 2023
875
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <map>
  5. #include <queue>
  6. #include "shoes.h"
  7. using namespace std;
  8. typedef long long  ll;
  9. const int maxn = 2e5 + 10;
  10. ll segment_tree[3 * maxn];
  11. void build_tree(int L, int R, int position) {
  12.     if(L == R) {
  13.         segment_tree[position] = 0;
  14.     }
  15.     else {
  16.         int middle = (L + R) / 2;
  17.         build_tree(L, middle, 2 * position);
  18.         build_tree(middle + 1, R, 2 * position + 1);
  19.         segment_tree[position] = segment_tree[2 * position] + segment_tree[2 * position + 1];
  20.     }
  21. }
  22. // L R i L R j L R
  23. ll query(int L, int R, int position, int i, int j) {
  24.     if(i <= L and R <= j) {
  25.         return segment_tree[position];
  26.     }
  27.     if(R < i or j < L) {
  28.         return 0;
  29.     }
  30.     int middle = (L + R) / 2;
  31.     return query(L, middle, 2 * position, i, j) + query(middle + 1, R, 2 * position + 1, i, j);
  32. }
  33. void update(int L, int R, int position, int idx, ll new_val) {
  34.     if(L == R) {
  35.         segment_tree[position] += new_val;
  36.         return;
  37.     }
  38.     int middle = (L + R) / 2;
  39.     if(idx <= middle) {
  40.         update(L, middle, 2 * position, idx, new_val);
  41.     }
  42.     else {
  43.         update(middle + 1, R, 2 * position + 1, idx, new_val);
  44.     }
  45.     segment_tree[position] = segment_tree[2 * position] + segment_tree[2 * position + 1];
  46. }
  47. ll count_swaps(vector<int> v) {
  48.     map<int, queue<int> > m;
  49.     vector<int> S;
  50.     int cnt = 0;
  51.     for(int i = 0; i < v.size(); i++) {
  52.         if(!m[v[i]].empty()) {
  53.             S.push_back(m[v[i]].front());
  54.             m[v[i]].pop();
  55.         }
  56.         else {
  57.             int r = 0;
  58.             if(v[i] > 0) {
  59.                 r = 1;
  60.             }
  61.             S.push_back(2 * cnt + r);
  62.             m[-v[i]].push(2 * cnt + (1 - r));
  63.             cnt++;
  64.            
  65.         }
  66.     }
  67.     build_tree(0, (int) v.size() + 1, 1);
  68.     ll res = 0;
  69.     for(int i = 0; i < (int) S.size(); i++) {
  70.         update(0, (int) v.size() + 1, 1, S[i], 1);
  71.         res += query(0, (int) v.size() + 1, 1, S[i] + 1, v.size());
  72.     }
  73.     return res;
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement