Cod sursa(job #1692712)

Utilizator lflorin29Florin Laiu lflorin29 Data 21 aprilie 2016 15:31:43
Problema Statistici de ordine Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>

using namespace std;
using tup = pair < int, vector<int>>;
using ll = long long;

int n, k;
int maxBits;

class Trie {
private:
  Trie *copii[2];
  int freq;
public:
  Trie() {
    memset(copii, 0, sizeof(copii));
    freq = 0;
  }
void add(int x) {
  Trie *T = this;
  for(int i = maxBits; i >= 0; --i) {
      bool b = x & (1<<i);
      if(!T->copii[b])
         T->copii[b] = new Trie;
      T = T->copii[b];
      T->freq++;
  }
}

int al() {
  Trie *T = this;
  int rez = 0;
  for(int i = maxBits; i >= 0; --i) {
     if(T->copii[0] != NULL && T->copii[0]->freq >= k)
        T = T->copii[0];
     else {
          rez += 1 << i;
          if(T->copii[0] != NULL)
          k -= T->copii[0]->freq;
          if(k == 0 || T->copii[1] == NULL)
             return rez;
          T = T->copii[1];
     }
  }
  return rez;
}

};

Trie *T = new Trie;
int main() {
  ifstream cin("sdo.in");
  ofstream cout("sdo.out");

  cin >> n >> k;
  vector<int>a(n);
  for(auto &x : a)
     cin >> x;
  for(auto &x : a)
     maxBits = max(maxBits, (int)log2(x));
  for(int i = 0; i < n; ++i)
     T->add(a[i]);

  cout << T->al();
  return 0;
}