TAAND - Editorial

Problem link : contest practice

Difficulty : Simple

Pre-requisites : Basic Math, Recursion, Bit Operations

Problem : Given an array find maximum AND(&) possible between any two elements.

Explanation

At first, let’s consider some partial solutions.

How to get 50 points

Here you can go through each possible pair and check what AND value is. And we can find what is the maximum AND possible. Complexity of this will be O(N*N).

n=input()
arr=[]
ans=-1
for i=1 to n:
	arr[i]=input()
for i=1 to n:
	for j=i+1 to n:
		ans = max( ans, arr[i]&arr[j] )

How to get 100 points

When we are ANDing two numbers, we would like to have a 1 at the most significant bit(MSB). So, first we’ll try to get a 1 at MSB. Now, suppose we denote A[i]=b_in,b_in-1…b_i0, where b_i’s are the bits that could be 1 or 0.

Let’s say S be the set of A[i] whose b_in is 1 and S’ be the set of A[i] whose b_in is 0. If size of S ≥ 2 we are sure that our answer will be maximum if we chose a pair of numbers from S, because n’th bit of their AND will be 1 for sure. So, we know our answer lies in S.

However, if size of S is less than 2, we can never have n’th bit 1 in our answer. So, we’ll have to continue with n’th bit as 0. Note that our answer will now be in S’.

Now, we know our answer is in S or S’ and we also know n’th bit of our answer. So, our new subproblem is to find (n-1)‘th bit of our answer using numbers in S or S’. We can write a recursive code for this.
What will be the complexity? For each of the n bits, we’ll traverse whole array to sort according to their bits. So O(n*N). We will be keeping n=30, because A[i] ≤ 109.

n=input()
arr=[]
flag[n]={}
for i=0 to n-1:
	arr[i]=input()
print foo(30)

def foo(level):  //this function will find the level'th bit
                //and accordingly return answer
	if level==-1:  // we already have solved for all bits. return 0 from here
		return 0
	Scount=0  // stores the size of set S
	ans=0 // the answer in decimal form
	for i=0 to n-1:
		if flag[i]==0:  // flag[i]=0 means arr[i] is available for us to use
			if (arr[i]&(1<<level)):	// level'th bit of arr[i] is 1
				Scount++
	if Scount>=2: // our answer's level'th bit will be 1
		ans += (1<<level)
		// but we also have to set the flag of unavailable numbers
		for i=0 to n-1:
			if (arr[i]&(1<<level))==0:  // level'th bit is 0, set the flag
				flag[i]=1
	return ans+foo(level-1);  // return the current answer + answer for the next bit

Solutions : setter tester

12 Likes

Why cant you just sort an array and try updating max for every two consecutive elements?
It passed to me.

10 Likes

I submitted this code in java.It gave NZEC.Can anybody tell why?

                                                                                                                                                                                                                               import java.io.BufferedReader;

                                                                                                                       import java.io.InputStreamReader;
 import java.io.PrintWriter;
import java.util.ArrayList;                                                                                                                                   import java.util.StringTokenizer;

 class AndOperation {

      long n=0;

      Integer arr[];  
                                                                                                                         public static void main(String[] args) throws Exception {
   
  
     AndOperation a=new AndOperation();

     a.solve();
   }

public void solve()throws Exception{
    long result=0;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    PrintWriter out=new PrintWriter(System.out);
    n=Integer.parseInt(br.readLine());
    arr=new Integer[(int)n];
 long ok=0;
    if(n>=2)
        {
      for(int i=0;i<n;i++)
         arr[i]=Integer.parseInt(br.readLine());
         }
  for(int i=0;i<n;i++){
       for(int j=i+1;j<n;j++){
            ok=arr[i]& arr[j];
               if(ok>result)
                 result=ok;
  
               }
          }
     System.out.println(result);

     br.close();
}

}

I have used this logic but unable to get ACCEPTED:

Sort numbers according to the range of power of 2 i.e 0-2, 2-4, 4-8, 8-16…and so on…

Now the last range in which we have at least two numbers contains those two integers

So just And the biggest two numbers in this range to get the answer

What is wrong with this?

It should be fail on testcase like 4 2 4 8 18 as pointed by abhisheklfs in problem’s comment , really weak test even my bruteforce got accepted.

2 Likes

ya this approach is wrong but it’s getting accepted.

1 Like

There must be some error in test cases as I did a simple sorting of numbers and took & of consecutive numbers and got an AC.But it’s is wrong solution as ans for test case :
3
10
3
19
should be 3 but it will give 2.
19 = 10011
10 = 01010
3 = 00011
ANS = 3
but by sorting ANS = 2
And it’s an AC code. So I think that the solutions should be rejudged.
Link : http://www.codechef.com/viewsolution/4392454

2 Likes

your logic fails for this test case:

4

32 31 3 3

Your output: 0

correct output:3 (because(3 (and) 3=3))…

2 Likes

The question says, 1 <= u < v <= N

1 Like

Yeah,i know it is wrong, but that is first that came up to my mind, so i tried to submit it, and it passed after 3 mins of contest, so wasnt thinking more about that problem.

1 Like

How can we solve this problem using Trie ? I read the blog and understood the idea of finding 2 elements whose XOR is maximum using trie. But if we have to use that concept here then if a particular bit is zero in the number then either of the branch of the trie can yield optimal answer. So how to choose a specific branch ?

I can’t understand your code. :frowning: , I can’t still understand the idea. I mean let’s say current bit is 0 , and this node has both left and right child. So why should we go to left ? I mean the right child also may produce the maximum ans can’t it.
Take for the example of inserting 0001,0111. Now if we try find and with 0011 now we go to left,left then what? I have got a 0 , and I could go both left and right. If we go left according to matching we get the max and is 1, but right has the answer 11.

1 Like

If the current bit of the number is 1 and current node also has an edge to 1 then moving to that edge is optimal. But if the current bit of the number is 0 then how to decide which edge we must take ? How is this optimal :
“if the current node has the left/right son according to the current bit of the number you go in that son”. if the current bit is 0 and current node has both left and right son : then how is choosing the son denoting 0 is optimal ?

my ans uses a different approach .
I just sorted the array and took and of the numbers and maintained that a&b <=max(a,b);
Is my approach correct?
my solution is link http://www.codechef.com/viewsolution/4386414

could anybody clear the doubt asked above ?

@Editorialist , if you would clear the matter or tell us that it isn’t possible it would be helpful. We are waiting here .

yep…wht is reasoning behind this.pls do explain .

I was bored to write a code on the formal algorithm I had developed i.e to check ranges of 2^n - where in you have to find the max range with at least two elements in that range and then compute AND operation on the closest two numbers. So instead, I checked the highest 5 elements and their AND operations with all elements and stored the max- giving AC(100) with O(10*n). Not very efficient and accurate but can be helpful in terms of saving time in contests.

http://www.codechef.com/viewsolution/4387562

1 Like

nice solution learned a lot about how to play with bits thnx man

my solution is easy one :slight_smile:

#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int main(){
int n;
cin>>n;
int a[n],b[n];
for(int i=0;i<n;i++){
cin>>a[i];
b[i]=log2(a[i]);
// cout<<b[i];
}
int mx=0,temp;
std::sort(a,a+n);
std::sort(b,b+n);
 
for(int i=n-1;i>=0;i--){
if(b[i]==b[i-1]){
mx=max(mx,a[i]&a[i-1]);
}
}
cout<<mx<<endl;
return 0;
}