CF1285D Dr. Evil Underscores

题目大意

你有一个数组${a_n}$,求一个数$x$ ,满足$\max{a_i \oplus x}$最小,输出这个最小值

题目分析

首先看到xor操作我们可以想到01trie, 接下来我们来分析如何用01trie计算答案

容易发现这样一个结论:如果一个节点的两个孩子都存在,那么这一位的异或值只能是$1$

设当前节点为$\texttt{now}$, 当前节点处在第$\texttt{dep}$位, 我们可以考虑这样一个过程

1.递归计算当前节点的孩子$\texttt{ch[now][0], ch[now][1]}$的答案$\texttt{ans[0], ans[1]}$,并求得$ans= \min {ans[0], ans[1] }$

2.若当前节点的两个孩子都存在,返回$ans+2^{dep}$,否则返回$ans$

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <bits/stdc++.h>

#define R register
#define ll long long
#define sum(a, b, mod) (((a) + (b)) % mod)

const int MaxN = 5e6 + 10;
const int lim = (1 << 29);

int n, cnt = 1, a[MaxN], num[MaxN], ch[MaxN][2];

inline void insert(int x)
{
int now = 1;
for (int i = lim; i; i >>= 1)
{
if (ch[now][!!(x & i)])
now = ch[now][!!(x & i)];
else
++num[now], now = ch[now][!!(x & i)] = ++cnt;
}
}

int query(int x, int k)
{
if (!num[x])
return 0;
int ans = 1e9;
if (ch[x][0])
ans = std::min(ans, query(ch[x][0], k >> 1));
if (ch[x][1])
ans = std::min(ans, query(ch[x][1], k >> 1));
return ((num[x] == 1) ? ans : (ans + k));
}

inline int read()
{
int x = 0;
char ch = getchar();
while (ch > '9' || ch < '0')
ch = getchar();
while (ch <= '9' && ch >= '0')
x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return x;
}

int main()
{
n = read();
for (int i = 1; i <= n; i++)
a[i] = read(), insert(a[i]);
printf("%d\n", query(1, lim));
return 0;
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×