fork download
  1. #include <stdio.h>
  2. #include <algorithm>
  3. #include <vector>
  4. using namespace std;
  5.  
  6.  
  7. class SegmentTree {
  8.  
  9. int sz;
  10. vector<int> t;
  11.  
  12. int query(int v, int vl, int vr, int l, int r) const {
  13. if (r < vl || vr < l)
  14. return 0;
  15. if (l <= vl && vr <= r)
  16. return t[v];
  17. int vm = vl + (vr - vl) / 2;
  18. int ql = query(2 * v + 1, vl, vm, l, r);
  19. int qr = query(2 * v + 2, vm + 1, vr, l, r);
  20. return ql + qr;
  21. }
  22.  
  23. void modify(int v, int vl, int vr, int pos, int val) {
  24. if (vl == vr) {
  25. t[v] += val;
  26. return;
  27. }
  28. int vm = vl + (vr - vl) / 2;
  29. if (pos <= vm)
  30. modify(2 * v + 1, vl, vm, pos, val);
  31. else
  32. modify(2 * v + 2, vm + 1, vr, pos, val);
  33. t[v] = t[2 * v + 1] + t[2 * v + 2];
  34. }
  35.  
  36. public:
  37.  
  38. SegmentTree(int size) {
  39. sz = size;
  40. t.resize(4 * sz);
  41. }
  42.  
  43. int size() {
  44. return sz;
  45. }
  46.  
  47. int query(int l, int r) const {
  48. return query(0, 0, sz - 1, l, r);
  49. }
  50.  
  51. void modify(int pos, int val) {
  52. modify(0, 0, sz - 1, pos, val);
  53. }
  54.  
  55. };
  56.  
  57.  
  58. class Event {
  59.  
  60. int type, index, x, y;
  61.  
  62. public:
  63.  
  64. Event(int type, int index, int x, int y) : type(type), index(index), x(x), y(y) {}
  65.  
  66. bool operator < (const Event &that) const {
  67. return x < that.x || x == that.x && type < that.type;
  68. }
  69.  
  70. void process(SegmentTree &st, vector<int> &answers) const {
  71. int k = st.query(y + 1, st.size() - 1);
  72. if (type == 1)
  73. answers[index] -= st.query(y + 1, st.size() - 1);
  74. if (type == 2)
  75. st.modify(y, 1);
  76. if (type == 3)
  77. answers[index] += st.query(y + 1, st.size() - 1);
  78. }
  79.  
  80. };
  81.  
  82.  
  83. int main() {
  84. vector<Event> scanLine;
  85.  
  86. int aSize, aMax = 0;
  87. scanf("%d", &aSize);
  88.  
  89. vector<int> a(aSize);
  90. for (int i = 0; i < aSize; i++) {
  91. scanf("%d", &a[i]);
  92. aMax = max(aMax, a[i]);
  93. scanLine.push_back(Event(2, -1, i, a[i]));
  94. }
  95.  
  96. SegmentTree st(aMax + 1);
  97.  
  98. int queriesCount;
  99. scanf("%d", &queriesCount);
  100.  
  101. for (int i = 0; i < queriesCount; i++) {
  102. int l, r, k;
  103. scanf("%d%d%d", &l, &r, &k);
  104. scanLine.push_back(Event(1, i, l - 1, k));
  105. scanLine.push_back(Event(3, i, r - 1, k));
  106. }
  107.  
  108. vector<int> answers(queriesCount);
  109. sort(scanLine.begin(), scanLine.end());
  110. for (int i = 0; i < scanLine.size(); i++)
  111. scanLine[i].process(st, answers);
  112.  
  113. for (int i = 0; i < queriesCount; i++)
  114. printf("%d\n", answers[i]);
  115. }
Success #stdin #stdout 0s 3488KB
stdin
5
5 1 2 3 4
3
2 4 1
4 4 4
1 5 2 
stdout
2
0
3