Advertisement
MaxObznyi

Kth one

Jun 18th, 2022
701
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. #include <iostream>
  2. #define int long long
  3. using namespace std;
  4.  
  5. const int N = 2e5 + 5;
  6.  
  7. int n, q, a[N], t[4 * N];
  8.  
  9. ///O(n)
  10. ///we want to calculate value for vertex v which represents the range [vl; vr]
  11. void build(int v, int vl, int vr) {
  12.     if (vl == vr) {
  13.         t[v] = a[vl];
  14.         return;
  15.     }
  16.     int vm = (vl + vr) / 2;
  17.     ///calculate left son
  18.     build(2 * v, vl, vm);
  19.     ///calculate right son
  20.     build(2 * v + 1, vm + 1, vr);
  21.  
  22.     ///combine them
  23.     t[v] = t[2 * v] + t[2 * v + 1];
  24. }
  25.  
  26.  
  27. ///O(log n)
  28. void update(int v, int vl, int vr, int pos, int val) {
  29.     if (vl == vr) {
  30.         ///vl == vr == pos
  31.         t[v] = val;
  32.         a[vl] = val;
  33.         return;
  34.     }
  35.     int vm = (vl + vr) / 2;
  36.     if (pos <= vm)
  37.         ///the position in the left half => calculate left son
  38.         update(2 * v, vl, vm, pos, val);
  39.     else
  40.         ///the position in the right half => calculate right son
  41.         update(2 * v + 1, vm + 1, vr, pos, val);
  42.  
  43.     ///combine them
  44.     t[v] = t[2 * v] + t[2 * v + 1];
  45. }
  46.  
  47. int find_kth(int v, int vl, int vr, int k) {
  48.     if (vl == vr)
  49.         return vl;
  50.  
  51.     int vm = (vl + vr) / 2;
  52.     if (t[2 * v] >= k)
  53.         return find_kth(2 * v, vl, vm, k);
  54.     else
  55.         return find_kth(2 * v + 1, vm + 1, vr, k - t[2 * v]);
  56. }
  57.  
  58.  
  59. signed main()
  60. {
  61.     cin >> n >> q;
  62.     for (int i = 1; i <= n; i++)
  63.         cin >> a[i];
  64.     build(1, 1, n);
  65.  
  66.     while (q--) {
  67.         int t;
  68.         cin >> t;
  69.         if (t == 1) {
  70.             int pos;
  71.             cin >> pos;
  72.             int val;
  73.             if (a[pos] == 0)
  74.                 val = 1;
  75.             else
  76.                 val = 0;
  77.  
  78.             update(1, 1, n, pos, val);
  79.         } else {
  80.             int k;
  81.             cin >> k;
  82.             cout << find_kth(1, 1, n, k) << "\n";
  83.         }
  84.     }
  85.  
  86.     return 0;
  87. }
  88.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement