【CodeForces 1365E --- Maximum Subsequence Value】

【CodeForces 1365E --- Maximum Subsequence Value】

题目来源:点击进入【CodeForces 1365E — Maximum Subsequence Value】

Description

Ridhiman challenged Ashish to find the maximum valued subsequence of an array a of size n consisting of positive integers.

The value of a non-empty subsequence of k elements of a is defined as ∑2i over all integers i≥0 such that at least max(1,k−2) elements of the subsequence have the i-th bit set in their binary representation (value x has the i-th bit set in its binary representation if ⌊x2i⌋mod2 is equal to 1).

Recall that b is a subsequence of a, if b can be obtained by deleting some(possibly zero) elements from a.

Help Ashish find the maximum value he can get by choosing some subsequence of a.

Input

The first line of the input consists of a single integer n (1≤n≤500) — the size of a.

The next line consists of n space-separated integers — the elements of the array (1≤ai≤1018).

Output

Print a single integer — the maximum value Ashish can get by choosing some subsequence of a.

Sample Input

3
2 1 3

Sample Output

3

Note

For the first test case, Ashish can pick the subsequence {2,3} of size 2. The binary representation of 2 is 10 and that of 3 is 11. Since max(k−2,1) is equal to 1, the value of the subsequence is 20+21 (both 2 and 3 have 1-st bit set in their binary representation and 3 has 0-th bit set in its binary representation). Note that he could also pick the subsequence {3} or {2,1,3}.

解题思路:

  • 题意:
    给n个数,要你选出k个数,对于二进制的第i位,如果你选的k个数里至少有max(1,k−2)个数字的二进制的第i位是1,答案就+2的i次方。 最后得到最大的和。
  • 思路
    当我们要选择时,我们可以发现明显的分界点就是max(1,k-2)。当k<3时当然就是1咯,那么为了满足最优情况,我们可以将所有数进行异或。只要在第i位有1那我就记进去,这样得到的就是最大值。
    当k>=3时,我们可以试想一下至少有k-2个第i位为1,那就是说我任选3个数必定至少有一个在第i位为1。那么我们只需要三重循环暴力找三个数使其最优即可。

AC代码(C++):

#include 
using namespace std;
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl '\n'
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int MAXN =505;
ll arr[MAXN];

int main(){
    int n;
    ll ans=0;
    cin >> n;
    for(int i=0;i<n;i++){
        cin >> arr[i];
    }
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            for(int k=0;k<n;k++){
                ans=max(ans,arr[i]|arr[j]|arr[k]);
            }
        }
    }
    cout << ans << endl;
    return 0;
}

你可能感兴趣的:(ACM)