fork download
  1. #include <stdio.h>
  2. #include <algorithm>
  3. #include <vector>
  4. using namespace std;
  5.  
  6.  
  7. class SegmentTreeFC {
  8.  
  9. int sz;
  10. vector< vector<int> > t, tl, tr;
  11.  
  12. void build(int v, int vl, int vr, const vector<int> &a) {
  13. if (vl == vr) {
  14. t[v].push_back(a[vl]);
  15. return;
  16. }
  17. int vm = vl + (vr - vl) / 2;
  18. build(2 * v + 1, vl, vm, a);
  19. build(2 * v + 2, vm + 1, vr, a);
  20.  
  21. int l = 2 * v + 1, r = 2 * v + 2;
  22. int ls = t[l].size(), rs = t[r].size(), ts = ls + rs;
  23. t[v].resize(ts);
  24. tl[v].resize(ts + 1);
  25. tr[v].resize(ts + 1);
  26. tl[v][ts] = ls;
  27. tr[v][ts] = rs;
  28. for (int i = ts - 1, li = ls - 1, ri = rs - 1; i >= 0; i--) {
  29. if (li < 0)
  30. t[v][i] = t[r][ri--];
  31. else if (ri < 0)
  32. t[v][i] = t[l][li--];
  33. else if (t[l][li] > t[r][ri])
  34. t[v][i] = t[l][li--];
  35. else
  36. t[v][i] = t[r][ri--];
  37. tl[v][i] = (li >= 0 && t[l][li] >= t[v][i] ? li : li + 1);
  38. tr[v][i] = (ri >= 0 && t[r][ri] >= t[v][i] ? ri : ri + 1);
  39. }
  40. }
  41.  
  42. int query(int v, int vl, int vr, int l, int r, int k, int ub) const {
  43. if (ub == -1)
  44. ub = upper_bound(t[v].begin(), t[v].end(), k) - t[v].begin();
  45. if (r < vl || vr < l)
  46. return 0;
  47. if (l <= vl && vr <= r)
  48. return vr - vl + 1 - ub;
  49. int vm = vl + (vr - vl) / 2;
  50. int ql = query(2 * v + 1, vl, vm, l, r, k, tl[v][ub]);
  51. int qr = query(2 * v + 2, vm + 1, vr, l, r, k, tr[v][ub]);
  52. return ql + qr;
  53. }
  54.  
  55. public:
  56.  
  57. SegmentTreeFC(const vector<int> &a) {
  58. sz = a.size();
  59. t.resize(4 * sz);
  60. tl.resize(4 * sz);
  61. tr.resize(4 * sz);
  62. build(0, 0, sz - 1, a);
  63. }
  64.  
  65. int query(int l, int r, int k) const {
  66. return query(0, 0, sz - 1, l, r, k, -1);
  67. }
  68.  
  69. };
  70.  
  71.  
  72. int main() {
  73. int aSize;
  74. scanf("%d", &aSize);
  75.  
  76. vector<int> a(aSize);
  77. for (int i = 0; i < aSize; i++)
  78. scanf("%d", &a[i]);
  79.  
  80. SegmentTreeFC st(a);
  81.  
  82. int queriesCount;
  83. scanf("%d", &queriesCount);
  84.  
  85. for (int i = 0; i < queriesCount; i++) {
  86. int l, r, k;
  87. scanf("%d%d%d", &l, &r, &k);
  88. printf("%d\n", st.query(l - 1, r - 1, k));
  89. }
  90. }
Success #stdin #stdout 0s 3496KB
stdin
5
5 1 2 3 4
3
2 4 1
4 4 4
1 5 2 
stdout
2
0
3