Блог пользователя DLN

Автор DLN, история, 4 года назад, По-английски

Problem Statement — Given an array count the no. of distinct pairs of elements such that their AND(&) is an exact power of 2.

array size <= 1e5 and 1 <= a[i] <= 2^12

Example — array -> [10 7 8 2 3] ; answer = 6

  • Проголосовать: нравится
  • +17
  • Проголосовать: не нравится

»
4 года назад, # |
Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

if bitwise and of x and y is a power of 2 then abs(x-y) must be a power of 2. so build a set of the given array first. then for each element p in the set, search the number of occurences of element p+pow(2,i) in the set for each i satisfying 0<=i<=12 and p&pow(2,i)=0.

»
4 года назад, # |
  Проголосовать: нравится +17 Проголосовать: не нравится

First keep the count of each number present in the array.
Simply brute force every pair (x,y) such that 1<=x<=y<=2^12 and check the bitwise AND of each pair.
If it is a power of 2, then do the following:
Case 1: if(x!=y)
then add count(x)*count(y) to the answer
Case 2: if(x==y)
then add (count(x)*(count(x)-1))/2 to the answer

»
4 года назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

can you please provide the question link? (i wanted to check if my solution works or not).

»
4 года назад, # |
  Проголосовать: нравится -8 Проголосовать: не нравится

I think we can use a trie and search for the required no. of pairs. Iterate over all the elements of the array. For a given no. in array there will be 12 possibilities of placing a 1 (not exactly 12, depends upon the position of 1s in the the selected numbers) , and traverse the trie and sum the total no. of such numbers which will make every bits 0 except one bit. I hope it will pass the time constraint!! If you want to study trie then follow this link: https://www.hackerearth.com/practice/data-structures/advanced-data-structures/trie-keyword-tree/tutorial/ Read whole advanced data structures, that will be quite beneficial for you!!