签到题(字典树)

签到题

[link](CSUSTOJ | 签到题)

题意

给定一个长度为n的数组n,需要你找到一个x,使得所有 a i ⊕ x a_i\oplus x aix最大的最小。

题解

建一个二进制的字典树,将所有的数插进去,对于某一位如果只有 0 或 1 0或1 01,我们就往这个有的走,对于答案的贡献是零,如果 0 和 1 0和1 01都有,我们发现这一位无论选什么对答案的贡献都是 1 < < ( 当 前 的 位 数 ) 1<<(当前的位数) 1<<(),所以将这个贡献加上,然后分别搜两个分支,选择小的即可。

Code

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <bitset>
#include <unordered_map>
#include <cmath> 
#include <stack>
#include <iomanip>
#include <deque> 
#include <sstream>
#define x first
#define y second
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 3e6 + 10, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
    e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
int a[N];
int tr[N][2];
int cnt[N];
int res = INF;
void insert(int x) {
    int p = 0;
    for (int i = 30; i >= 0; i -- ) {
        int u = x >> i & 1;
        if (!tr[p][u]) tr[p][u] = ++ idx;
        p = tr[p][u];
    }
}
int query(int u, int p) {
    int sum = 0;
    for (; u >= 0; u -- ) {
        if (tr[p][1] && tr[p][0]) return sum + (1 << u) + min(query(u - 1, tr[p][1]), query(u - 1, tr[p][0]));
        else if (tr[p][0]) p = tr[p][0];
        else   p = tr[p][1];
    } 
    return sum;
}
int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    cin >> n;
    for (int i = 1; i <= n; i ++ ) {
        int x; cin >> x;
        insert(x);
    }
    cout << query(30, 0) << endl;
    return 0; 
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值