Table of Contents

ExplanationImplementation

Explanation

Let | denote the bitwise OR operation and &\& denote the bitwise AND operation.

The answer is equivalent to finding an xx such that x=aj&akx=a_j\&a_k and aixa_i|x is maximized for some three indices i<j<ki<j<k.

Note that xx can be binary searched since 2b>20+21++2b12^b>2^0+2^1+\dots+2^{b-1}, so we can loop through each 2b2^b in decreasing order and check if there exists an answer for zz such that zz is a superset of x2bx|2^b. When we reach a bit 2b2^b such that it is contained in aia_i, it doesn't matter whether it is in the final xx since aixa_i|x already contains 2b2^b.

In other words, we have to find a pair (j,k)(j, k) such that i<j<ki<j<k and aj&aka_j\&a_k is a superset of x2bx|2^b. This is equivalent to finding jj and kk such that j,k>ij, k>i, ajx2ba_j\supseteq x|2^b, and akx2ba_k\supseteq x|2^b. This can be done by Sum Over Subsets DP (or supersets in this case) by maintaining fxf_x and gxg_x, which stores the two largest jj such that ajxa_j\supseteq x.

Implementation

Time Complexity: O(NlogA+AlogA)\mathcal{O}(N\log A + A\log A) where A=maxaiA=\max a_i.

C++

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6;
const int B = 21;
const int A = 1 << B;
int main() {
int n;
cin >> n;

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!