fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long
  4. vector<int> vec;
  5. int n, k;
  6.  
  7. int recur(int l, int r) {
  8. int ans = 0;
  9. if (l + 1 >= r) {
  10. return ans;
  11. }
  12. int mid = (l + r) / 2;
  13. ans += recur(l, mid);
  14. ans += recur(mid, r);
  15. cout << l << " " << r << endl;
  16. // Debugging output
  17. // cout << l << " " << r << endl;
  18.  
  19. // Count inversions
  20.  
  21. // int ans1 = 0;
  22. for(int i = l, j = mid; i < mid; i++){
  23. while(j < r && vec[i] >= vec[j] + k) j++;
  24. ans += j - mid;
  25. }
  26.  
  27. // cout << ans1 << endl;
  28. inplace_merge(vec.begin() + l, vec.begin() + mid, vec.begin() + r);
  29. return ans;
  30. }
  31.  
  32. signed main() {
  33. cin.tie(0);
  34. ios::sync_with_stdio(false);
  35. cin >> n >> k;
  36. vec.resize(n);
  37. for (int i = 0; i < n; i++) {
  38. cin >> vec[i];
  39. }
  40. cout << recur(0, n) << endl;
  41. }
Success #stdin #stdout 0s 5276KB
stdin
6 2
1 2 3 4 5 6
stdout
1 3
0 3
4 6
3 6
0 6
0