求n个数中两数异或的最大值(字母树)

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <set>
#define INF 0x3f3f3f3f3f3f3f
using namespace std;
const int MAXN = 2e5 + 10;

int node;
int next[MAXN][2];
int ed[MAXN];
void add(int cur, int k)
{
    memset(next[node], 0, sizeof(next[node]));
    next[cur][k] = node++;
    //cout << "~~" << node << " ";
}

int cal(int x)
{
    int cur = 0;
    for (int i = 30; i >= 0; --i) {
        int k = (x >> i) & 1;
        if (next[cur][1-k]) cur = next[cur][1-k];
        else cur = next[cur][k];
    }
    //cout << x << " " << ed[cur] << endl;
    return (x ^ ed[cur]);
}

int main()
{
    int n;
    cin >> n;
    int a[MAXN];
    node = 1;
    next[0][0] = next[0][1] = 0;
    memset(ed, 0, sizeof(ed));
    for (int i = 0; i < n; ++i) {
        scanf("%d", &a[i]);
        int cur = 0;
        for (int j = 30; j >= 0; --j) {
            int k = (a[i] >> j) & 1;
            if (next[cur][k] == 0) add(cur, k);
            cur = next[cur][k];
        }
        ed[cur] = a[i];
    }
    int ans = 0;
    for (int i = 0; i < n; ++i)
        ans = max(ans, cal(a[i]));
    cout << ans << endl;


    int ans2 = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            ans2 = max(ans2, a[i] ^ a[j]);
        }
    }
    cout << ans2 << endl;

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值