Skip to main content

Trie problem in Codeforces Round #470

I could not solve the D. Perfect Security in last night's codeforces contest.
In the morning I finally understood that the problem was actually a Trie problem. To solve the problem I used a structure name trie which has two trie type structure zero and one and a counter name cnt. For each trie node the cnt stores the number of zeros or ones in that node.
As problem says to minimum XOR values. So, the search operation traversing the same bit node ( bit 1 for one and 0 for zero trie type node ) of the Trie tree. If the search operation fail to found the same bit node with a positive counter values, then the operation check for reverse bit node with positive counter.
If the conditions are not satisfied, it stops the search operation. For Trie type node one turned on the return value bit position. value | = (1 << position) .
The search operation always reduce the traversing nodes counter by 1, So no need to delete operation for each keys.

Comments

Popular posts from this blog

Gray Code

A Gray code is a list of all 2^n  bit strings of length , where any two successive strings differ in exactly one bit (i.e., their Hamming distance is one).  source   The problem is, how to generate Gray Code for a given length n.  When n = 2 , Gray Code :  00  01  11  10 When n = 3, Gray Code : 000 001 011 010 110 111 101 100 000(0) position Gray code string 000  001(1) -> 001  010(2) -> 011  011(3) -> 010 .....  Key observation -  For the  K position, the Gray code string is S .   if i and (i+1)- th bit of K is equal then i- th char of S will be  ' 0 ', otherwise, it will be ' 1 '.   Code :               int n; cin >> n;     for(int i = 0; i < (1 << n); i++) {         int value =  ( i ^ (i >> 1) ) ;         string s = "";         for(int j = 0; j < n; j++) {             if( value & (1 << j) )s.push_back('1');             else s.push_back('0');         }         reverse( s.begin(), s.end() );      

Histogram - LOJ

It's a well-known problem and the well-known solution is using a stack. I tried to solve it by segment tree( iterative version for building tree ) and got TLE. Hope I can optimize the code.  TLE CODE