Advertisement
Guest User

Number of elements <x, segtree from top

a guest
Dec 1st, 2015
1,495
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. #include <functional>
  2. #include <algorithm>
  3. #include <iostream>
  4. #include <numeric>
  5. #include <cassert>
  6. #include <cstdlib>
  7. #include <cstring>
  8. #include <string>
  9. #include <cstdio>
  10. #include <vector>
  11. #include <ctime>
  12. #include <queue>
  13. #include <set>
  14. #include <map>
  15. using namespace std;
  16. #define forn(i, n) for (int i = 0; i < (int)(n); ++i)
  17. #define fore(i, b, e) for (int i = (int)(b); i <= (int)(e); ++i)
  18. #define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
  19. #define mp make_pair
  20. #define pb push_back
  21. #define fi first
  22. #define se second
  23. #define all(x) (x).begin(), (x).end()
  24. typedef vector<int> vi;
  25. typedef pair<int, int> pii;
  26. typedef long long i64;
  27. typedef unsigned long long u64;
  28. const int inf = 1e9+100500;
  29.  
  30. int cnt = 0;
  31.  
  32. struct node {
  33.     int l, r;
  34.     node *L, *R;
  35.     vi val;
  36.  
  37.     node(int l, int r, int a[]) : l(l), r(r) {
  38.         if (l == r) {
  39.             L = R = NULL;
  40.             val = {a[l]};
  41.         } else {
  42.             L = new node(l, (l+r)/2, a);
  43.             R = new node((l+r)/2+1, r, a);
  44.             val.resize(r-l+1);
  45.             merge(all(L->val), all(R->val), val.begin());
  46.         }
  47.     }
  48.  
  49.     // # if elements < x
  50.     int get(int lq, int rq, int x) {
  51.         if (lq <= l && rq >= r) {
  52.             ++cnt;
  53.             return lower_bound(all(val), x) - val.begin();
  54.         } else if (rq < l || lq > r) {
  55.             return 0;
  56.         } else {
  57.             return L->get(lq, rq, x) + R->get(lq, rq, x);
  58.         }
  59.     }
  60. };
  61.  
  62. int a[500000];
  63.  
  64. int main() {
  65. #ifdef HOME
  66.     freopen("input.txt", "r", stdin);
  67. #endif
  68.  
  69.     int n;
  70.     cin >> n;
  71.     forn(i, n) cin >> a[i];
  72.     node *t = new node(0, n-1, a);
  73.     cerr << "built @" << clock()/1000 << " ms" << endl;
  74.     int m;
  75.     cin >> m;
  76.     int ss = 0;
  77.     forn(i, m) {
  78.         int l, r, x;
  79.         cin >> l >> r >> x;
  80.         int a = t->get(l, r, x);
  81.         ss += a;
  82.     }
  83.     cout << ss << endl;
  84.     cout << "cnt = " << cnt << endl;
  85.  
  86. #ifdef HOME
  87.     cerr << "Time elapsed: " << clock() / 1000 << " ms" << endl;
  88. #endif
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement