Advertisement
BotByte

BIT.cpp

May 3rd, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. /*
  2.     Algorithm : Binary Indexed Tree
  3.     Problem : Counting Inversions in an array of length N
  4. */
  5.  
  6. #include <bits/stdc++.h>
  7.  
  8. using namespace std;
  9.  
  10. #define MAX 65540
  11. int BIT[MAX];
  12.  
  13. void update(int pos, int val)
  14. {
  15.     for(; pos<MAX; pos+= pos&(-pos)){
  16.         BIT[pos] += val;
  17.     }
  18. }
  19.  
  20. int query(int pos)
  21. {
  22.     int sum = 0;
  23.     for(; pos>0; pos-= pos&(-pos)){
  24.         sum += BIT[pos];
  25.     }
  26.     return sum;
  27. }
  28.  
  29. long long rangeQuery(int l, int r)
  30. {
  31.     long long sum1 = query(r);
  32.     long long sum2 = query(l-1);
  33.     return sum1-sum2;
  34. }
  35.  
  36. int main()
  37. {
  38.     int n;
  39.     scanf("%d", &n);
  40.     vector<pair<int, int> > V;
  41.     for(int i=0; i<n; i++){
  42.         int val;
  43.         scanf("%d", &val);
  44.         V.push_back(make_pair(val, i));
  45.     }
  46.     sort(V.begin(), V.end());
  47.     int arr[n];
  48.     int sz = 1;
  49.     int idx = V[0].second;
  50.     arr[idx] = sz;
  51.     for(int i=1; i<n; i++){
  52.         if(V[i].first != V[i-1].first){
  53.             sz++;
  54.         }
  55.         int idx = V[i].second;
  56.         arr[idx] = sz;
  57.     }
  58.     memset(BIT, 0, sizeof BIT);
  59.     long long ans = 0;
  60.     for(int i=0; i<n; i++){
  61.         int val = arr[i];
  62.         update(val, 1);
  63.         ans += rangeQuery(val+1, MAX-1);
  64.     }
  65.     printf("%lld\n", ans);
  66. }
  67.  
  68. /*
  69.     5
  70.     2 3 1 5 4
  71.  
  72.     3
  73. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement