Cod sursa(job #1692710)

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

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

int n, k;

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 = 30; 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 = 30; 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;
  for(int i = 0; i < n; ++i) {
     int x; cin >> x;
     T->add(x);
  }

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