I was just solving problems and came upon this one
Given an array A consisting of N integers - A1, A2....AN. You have to find the value of Σ MAX(i,j) * F(i,j) where 1 ≤ i < j ≤ N.
MAX(i,j) is defined as max(Ai,Ai+1...Aj).
F(i,j) is defined as:
F(i,j) will be 1 if
(Ai&Aj) = Aj or (Ai&Aj) = Ai
F(i,j) will be 0, otherwise. Here & denotes the bitwise AND operator.
reference: GOODPROB
I wrote a fairly simple solution and got 40 points, i.e. it could not handle large inputs in the required 2 seconds time.
This was my code
#include <iostream>
using namespace std;
int max(int *A, int x,int y){
int m=A[x];
while(x<=y){
if(A[x]>m)
m=A[x];
x++;
}
return m;
}
int F(int *A,int i,int j){
return ((A[i]&A[j]) == A[j] or (A[i]&A[j]) == A[i])?1:0;
}
int main() {
long N;
cin>>N;
int *A = new int[N];
for(int i=0;i<N; i++)
cin>>A[i];
long m=0;
for(int j=0;j<N;j++)
for(int i=0;i<j; i++)
m+= F(A,i,j)?max(A,i,j)*F(A,i,j):0;
cout<<m<<endl;
return 0;
}
I checked the successful submitions there but those made me go panic. I couldn't even imagine such large solution for this fairly simple looking problem. Can anyone come up with a solution simple enough to understand.