bhupixb

Merge Sort Tree

Jan 23rd, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define P pair < int, int >
  5. #define s second
  6. #define f first
  7. #define pb push_back
  8. #define all(v) v.begin(), v.end()
  9. #define rep(i,a,n) for(int i = a; i <= n; ++i)
  10. #define lb(v, x) lower_bound(all(v), x) - v.begin()
  11. #define up(v, x) upper_bound(all(v), x) - v.begin()
  12. #define fo(i, n) for (int i = 1; i <= n; ++i)
  13.  
  14. const int N = 1e4 + 5;
  15. int a[N];
  16. class merge_sort_tree{
  17. vector < int > tree[N << 2];
  18. public:
  19. void build(int l, int r, int node){
  20. if(l == r){
  21. tree[node].pb(a[l]);
  22. return ;
  23. }
  24. int mid = l + r >> 1, lc = node + node, rc = 1 + lc;
  25. build(l, mid, lc); build(mid + 1, r, rc);
  26.  
  27. merge(all(tree[lc]), all(tree[rc]), back_inserter(tree[node]));
  28. }
  29. int query(int l, int r, int ql, int qr, int val, int node){
  30. if(qr < l || r < ql)
  31. return 0;
  32. if(ql <= l and r <= qr){
  33. //returns number of elements strictly less than VAL(val)
  34. int L = lower_bound(all(tree[node]), val) - tree[node].begin();
  35. return L;
  36. }
  37. int mid = l + r >> 1, lc = node + node, rc = 1 + lc;
  38.  
  39. return (query(l, mid, ql, qr, val, lc)
  40. + query(mid + 1, r, ql, qr, val, rc));
  41. }
  42. };
  43. int main(){
  44. ios_base::sync_with_stdio(NULL);
  45. cin.tie(NULL);
  46. cout.tie(NULL);
  47. merge_sort_tree obj;
  48. int n, q, l, r, k;
  49. cin >> n >> q;
  50. fo(i, n)
  51. cin >> a[i];
  52.  
  53. obj.build(1, n, 1);
  54. return 0;
  55. }
Add Comment
Please, Sign In to add comment