这里放的是Hard的题面,思路Easy和Hard都有
前缀知识戳这
D2. 388535 (Hard Version)
题面
Easy版本的不同在于
L
=
0
L=0
L=0;
思路
首先考虑Easy版本的情况,那么原序列中必然存在一个 0 0 0,那么操作以后这个数就是 x x x;
题目的数据肯定是有解的(因为没有让我们判断无解的情况),那么也就是说我们求出 x x x以后,异或每个数得到的必然是序列 [ L , . . . , R ] [L,...,R] [L,...,R]的某种排序;
那么实际上我们只需要假设当前的数就是 x x x,然后去找和它异或的最大值( x ⊕ r ) x \oplus r) x⊕r),判断得出是值是否是 r r r即可;
Hard版本
同理我们只需要假设当前数是 x ⊕ L x \oplus L x⊕L,然后求当前数的异或最大值与异或最小值,判断是否是 L L L和 R R R即可;
Code
Easy
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
int a[N];
int son[N*20][2],idx;
void insert(int x){
int now = 0;
for(int i=18;i>=0;--i){
int v = (x >> i) & 1;
if(!son[now][v]) son[now][v] = ++idx;
now = son[now][v];
}
}
//异或最大值
int queryMax(int x){
int now = 0,ret = 0;
for(int i=18;i>=0;--i){
int v = (x >> i) & 1;
if(son[now][v^1]){
now = son[now][v^1];
ret = (ret << 1) + (v^1);
}
else{
now = son[now][v];
ret = (ret << 1) + v;
}
}
return ret;
}
void solve(){
int l,r;
cin >> l >> r;
for(int i=0;i<=idx;++i){
son[i][0] = son[i][1] = 0;
}
idx = 0;
for(int i=l;i<=r;++i)
cin >> a[i],insert(a[i]);
for(int i=l;i<=r;++i){
int x = a[i];
if((queryMax(x)^x) == r){
cout << x << '\n';
return;
}
}
}
signed main(){
std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int t;
cin >> t;
while(t--)
solve();
return 0;
}
Hard
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
int a[N];
int son[N*20][2],idx;
void insert(int x){
int now = 0;
for(int i=18;i>=0;--i){
int v = (x >> i) & 1;
if(!son[now][v]) son[now][v] = ++idx;
now = son[now][v];
}
}
//异或最大值
int queryMax(int x){
int now = 0,ret = 0;
for(int i=18;i>=0;--i){
int v = (x >> i) & 1;
if(son[now][v^1]){
now = son[now][v^1];
ret = (ret << 1) + (v^1);
}
else{
now = son[now][v];
ret = (ret << 1) + v;
}
}
return ret;
}
//异或最小值
int queryMin(int x){
int now = 0,ret = 0;
for(int i=18;i>=0;--i){
int v = (x>>i)&1;
if(son[now][v]){
now = son[now][v];
ret = (ret << 1) + v;
}
else{
now = son[now][v^1];
ret = (ret << 1) + (v^1);
}
}
return ret;
}
void solve(){
int l,r;
cin >> l >> r;
for(int i=0;i<=idx;++i){
son[i][0] = son[i][1] = 0;
}
idx = 0;
for(int i=l;i<=r;++i)
cin >> a[i],insert(a[i]);
for(int i=l;i<=r;++i){
int x = a[i]^l;
if((queryMax(x)^x) == r && (queryMin(x)^x) == l){
cout << x << '\n';
return;
}
}
}
signed main(){
std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int t;
cin >> t;
while(t--)
solve();
return 0;
}