異或最大值升級(jí)版

Description

給 n 個(gè)數(shù) a[1] ~ a[n],求 (a[i] + a[j]) ⊕ a[k] 的最大值,其中 i, j, k 為互不相同的序號(hào),“⊕”表示按位異或。

Input

多組數(shù)據(jù),每組數(shù)據(jù)第一行一個(gè) n ,第二行 n 個(gè)正整數(shù) a[i]。

其中 3 <= n <= 2000, 0 <= a[i] <= 10^9。

Output

每組數(shù)據(jù)輸出最大的結(jié)果。

Sample Input

3
3 1 2
5
1 7 6 8 9

Sample Output

6
24

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<algorithm>
const int maxn = 2e3 + 10;
int a[maxn << 5 | 1], n;
struct Node
{
    int cnt;
    int nex[2];
    void Init() {nex[0] = nex[1] = -1; cnt = 0;}
};
Node trie[maxn << 5];
int tp;
void Insert(int x)
{
    int now = 0;
    for(int i = 30; i >= 0; i --)
    {
        int ith1 = x >> i & 1;
        if(trie[now].nex[ith1] == -1) 
        {
            trie[tp].Init();
            trie[now].nex[ith1] = tp ++;
        }
        trie[now].cnt ++;
        now = trie[now].nex[ith1];        
    }
    trie[now].cnt ++;
}
int Find(int x, int rev=0)
{
    int now = 0, tmpx = 0;
    for(int i = 30; i >= 0; i --)
    {
        int ith1 = (x >> i & 1) ^ rev;
        if(rev && (trie[now].nex[ith1] == -1 || !trie[trie[now].nex[ith1]].cnt)) ith1 ^= 1;
        if(trie[now].cnt == 0 || trie[now].nex[ith1] == -1) return -1;
        now = trie[now].nex[ith1];
        tmpx |= ith1 << i;     
    }
    return trie[now].cnt > 0 ? tmpx : -1;
}
void Delete(int x)
{
    int now = 0;
    for(int i = 30; i >= 0; i --)
    {
        int ith1 = x >> i & 1;
        trie[now].cnt --;
        now = trie[now].nex[ith1];
    }
    trie[now].cnt --;
}
int main()
{
    while(scanf("%d", &n) != EOF)
    {
        trie[0].Init();
        tp = 1;
        for(int i = 0; i < n; i ++)
            scanf("%d", &a[i]), Insert(a[i]);
        int ans = 0;
        for(int i = 0; i < n; i ++)
        {
            Delete(a[i]);
            for(int j = i + 1; j < n; j ++)
            {
                Delete(a[j]);
                ans = std::max(ans, Find(a[i] + a[j], 1) ^ (a[i] + a[j]));
                Insert(a[j]);
            }
            Insert(a[i]);
        }
        printf("%d\n", ans);
    }
    return 0;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容