bhupixb

Inversion Count using BIT

Aug 15th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int N =1e5 + 5;
  4. int inv(int pos, int BIT[]){
  5. int count = 0;
  6. while(pos > 0){
  7. count += BIT[pos];
  8. pos -= (pos & (-pos));
  9. }
  10. return count;
  11. }
  12. void upd(int pos, int BIT[], int n){
  13.  
  14. while(pos <= n ){
  15. BIT[pos]++;
  16. pos += (pos & (-pos));
  17. }
  18.  
  19. }
  20. int main(){
  21. int t;
  22. scanf("%d", &t);
  23. while(t--){
  24. int n, i;long long int ans = 0;
  25. scanf("%d", &n);
  26. int BIT[N] = {0};
  27. vector < int > arr(n), v(n);
  28. for(i = 0;i < n; i++)
  29. scanf("%d", &arr[i]), v[i] = arr[i];
  30.  
  31. sort(v.begin(), v.end());
  32.  
  33. for(i = 0; i < n; i++)
  34. arr[i] = lower_bound(v.begin(), v.end(), arr[i]) - v.begin() + 1;
  35.  
  36. for(i = n-1; i >= 0; i--)
  37. ans += inv(arr[i]-1, BIT), upd(arr[i], BIT, n);
  38. cout << ans << '\n';
  39. }
  40.  
  41. return 0;
  42. }
Add Comment
Please, Sign In to add comment