Advertisement
Alex_tz307

Trie pentru mex

Mar 6th, 2021
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. class node {
  6.     public:
  7.         node *child[2];
  8.         bool is_full = false;
  9.         int cnt = 0;
  10.  
  11.         node() {
  12.             child[0] = nullptr;
  13.             child[1] = nullptr;
  14.         }
  15. };
  16.  
  17. node *create(node *&n) {
  18.     if(!n)
  19.         n = new node();
  20.     return n;
  21. }
  22.  
  23. void add(int val, int level, node *n) {
  24.     if(level == -1) {
  25.         ++n->cnt;
  26.         n->is_full = true;
  27.         return;
  28.     }
  29.     int curr_bit = (val & (1 << level)) >> level;
  30.     add(val, level - 1, create(n->child[curr_bit]));
  31.     n->is_full = create(n->child[0])->is_full && create(n->child[1])->is_full;
  32.     n->cnt = create(n->child[0])->cnt + create(n->child[1])->cnt;
  33. }
  34.  
  35. void rem(int val, int level, node *n) {
  36.     if(level == -1) {
  37.         --n->cnt;
  38.         n->is_full = n->cnt > 0;
  39.         return;
  40.     }
  41.     int curr_bit = (val & (1 << level)) >> level;
  42.     rem(val, level - 1, create(n->child[curr_bit]));
  43.     n->is_full = create(n->child[0])->is_full && create(n->child[1])->is_full;
  44.     n->cnt = create(n->child[0])->cnt + create(n->child[1])->cnt;
  45. }
  46.  
  47. int query(int val, int level, node *n) {
  48.     if(n->is_full)
  49.         return -1;
  50.     if(n->cnt == 0)
  51.         return val;
  52.     int curr_bit = (val & (1 << level)) >> level;
  53.     int ans = query(val, level - 1, create(n->child[curr_bit]));
  54.     if(curr_bit == 0 && ans == -1)
  55.         ans = query((val >> level << level) | (1 << level), level - 1, create(n->child[1]));
  56.     return ans;
  57. }
  58.  
  59. node root;
  60.  
  61. int main() {
  62.     ios_base::sync_with_stdio(false);
  63.     cin.tie(nullptr);
  64.     cout.tie(nullptr);
  65.     int N, M;
  66.     cin >> N >> M;
  67.     vector<int> a(N + 1);
  68.     for(int i = 1; i <= M; ++i) {
  69.         cin >> a[i];
  70.         add(a[i], 22, &root);
  71.     }
  72.     int ans = query(0, 22, &root);
  73.     for(int i = M + 1; i <= N; ++i) {
  74.         cin >> a[i];
  75.         rem(a[i - M], 22, &root);
  76.         add(a[i], 22, &root);
  77.         ans = min(ans, query(0, 22, &root));
  78.     }
  79.     cout << ans << '\n';
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement