Explanation
Let denote the bitwise OR operation and denote the bitwise AND operation.
The answer is equivalent to finding an such that and is maximized for some three indices .
Note that can be binary searched since , so we can loop through each in decreasing order and check if there exists an answer for such that is a superset of . When we reach a bit such that it is contained in , it doesn't matter whether it is in the final since already contains .
In other words, we have to find a pair such that and is a superset of . This is equivalent to finding and such that , , and . This can be done by Sum Over Subsets DP (or supersets in this case) by maintaining and , which stores the two largest such that .
Implementation
Time Complexity: where .
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!