Advertisement
STANAANDREY

minimum nr of adjacent swaps to mk arr2==arr1

May 8th, 2023 (edited)
774
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. constexpr int NMAX = 1e5 + 3;
  4. int n, arr1[NMAX], arr2[NMAX];
  5. int posOfElemIn2nd[NMAX], posOfIthFrom1stIn2nd[NMAX];
  6.  
  7. void readArr(int arr[NMAX]) {
  8.     for (int i = 1; i <= n; i++) {
  9.         scanf("%d", arr + i);
  10.     }
  11. }
  12.  
  13. struct SegTree {
  14.     int tree[4 * NMAX];
  15.  
  16.     void update(int node, int le, int ri, int val) {
  17.         if (le == ri) {
  18.             tree[node]++;
  19.             return;
  20.         }
  21.         int mid = (le + ri) / 2;
  22.         int leSon = node * 2, riSon = node * 2 + 1;
  23.         if (val <= mid) {
  24.             update(leSon, le, mid, val);
  25.         } else {
  26.             update(riSon, mid + 1, ri, val);
  27.         }
  28.         tree[node] = tree[leSon] + tree[riSon];
  29.     }
  30.  
  31.     int query(int node,int le, int ri, int qle, int qri) {
  32.         if (qle > ri || qri < le) {
  33.             return 0;
  34.         }
  35.         if (qle <= le && ri <= qri) {
  36.             return tree[node];
  37.         }
  38.         int mid = (le + ri) / 2;
  39.         int leSon = node * 2, riSon = node * 2 + 1;
  40.         int leAns = query(leSon, le, mid, qle, qri);
  41.         int riAns = query(riSon, mid + 1, ri, qle, qri);
  42.         return leAns + riAns;
  43.     }
  44. };
  45.  
  46. int main() {
  47.     scanf("%d", &n);
  48.     readArr(arr1);
  49.     readArr(arr2);
  50.  
  51.     for (int i = 1; i <= n; i++) {
  52.         posOfElemIn2nd[arr2[i]] = i;
  53.     }
  54.     for (int i = 1; i <= n; i++) {
  55.         posOfIthFrom1stIn2nd[i] = posOfElemIn2nd[arr1[i]];
  56.     }
  57.  
  58.     int ans = 0;
  59.     SegTree segTree;
  60.     for (int i = n; i > 0; i--) {
  61.         ans += segTree.query(1, 1, n, 1, posOfIthFrom1stIn2nd[i]);
  62.         segTree.update(1, 1, n, posOfIthFrom1stIn2nd[i]);
  63.     }
  64.     printf("%d\n", ans);
  65.     return 0;
  66. }
  67.  
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement