Cod sursa(job #1308371)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 3 ianuarie 2015 23:49:56
Problema Statistici de ordine Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <bits/stdc++.h>

using namespace std;

struct Trie
{
    Trie *sons[2];
    int cnt;
    int size;

    Trie()
    {
        cnt = 0;
        size = 0;
        sons[0] = sons[1] = NULL;
    }
};

Trie *R;

void insert( Trie *&root, int b, int nr )
{
    if ( b == -1 )
    {
        root->cnt++;
        root->size = root->cnt;
    }
    else
    {
        int p = (bool)( nr & ( 1 << b ) );

        if ( root->sons[p] == NULL )
            root->sons[p] = new Trie();

        insert( root->sons[p], b - 1, nr );

        if ( root->sons[0] != NULL )
            root->size += root->sons[0]->size;

        if ( root->sons[1] != NULL )
            root->size += root->sons[1]->size;
    }
}

void kth_order( Trie *&root, int b, int k, int &sol )
{
    if ( b != -1 )
    {
        if ( root->sons[0] != NULL && root->sons[0]->size >= k )
        {
            kth_order( root->sons[0], b - 1, k, sol );
        }
        else
            if ( root->sons[1] != NULL )
            {
                int cat = 0;

                if ( root->sons[0] != NULL )
                    cat = root->sons[0]->size;

                sol |= ( 1 << b );

                kth_order( root->sons[1], b - 1, k - cat, sol );
            }
    }

}

int N, K, a;

int main()
{
    ifstream in("sdo.in");
    ofstream out("sdo.out");

    ios_base::sync_with_stdio( false );

    in >> N >> K;

    R = new Trie();

    for ( int i = 1; i <= N; ++i )
    {
        in >> a;
        insert( R, 31, a );
    }

    int sol = 0;
    kth_order( R, 31, K, sol );

    out << sol << "\n";

    return 0;
}