[蓝桥杯] 异或和之差

题目描述:
https://www.lanqiao.cn/problems/3524/learning/
思路: : 01trie求最大(最小)异或对 。 先看一边, 我们对数组进行一次异或前缀和,得到异或前缀数组b[N], 从b中选两个数,相当于取一段区间,这就可以使用01trie去找最大(最小)异或对了。使用4个数组lmax[N], lmin[N],rmax[N],rmin[N]分别去记录1 – N位置和N – 1位置的最大异或值和最小异或值。最后对每个位置去做一次max - min 即可。

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
//#define int long long
#define ios ios::sync_with_stdio(false); cin.tie(0);cout.tie(0)
const int N = 2e5+5;
int a[N], b[N], b1[N], lch[N*21][2],rch[N*21][2], lidx, ridx, n;
int lmax[N], rmax[N], lmin[N], rmin[N];
void insert(int x, int ch[][2], int &idx){
    int p = 0;
    for(int i = 20; i >= 0; i--){
        int j = x >> i & 1;
        if(!ch[p][j]) ch[p][j] = ++idx;
        p = ch[p][j];
    }
}
int query(int x, int ch[][2]){
    int p = 0, res = 0;
    for(int i = 20; i >= 0; i--){
        int j = x >> i & 1;
        if(ch[p][!j]){
            res += 1 << i;
            p = ch[p][!j];
        }else p = ch[p][j];
    }
    return res;
}
int querym(int x, int ch[][2]){
    int p = 0, res = 0;
    for(int i = 20; i >= 0; i--){
        int j = x >> i & 1;
        if(ch[p][j]){
            p = ch[p][j];
        }else{
            res += 1 << i;
            p = ch[p][!j];
        }
    }
    return res;
}



void solve(){
    cin >> n;
    for(int i = 1; i <= n; i++){
        cin >> a[i];
        b[i] = b[i - 1] ^ a[i];
    }
    for(int i = n; i >= 1; i--){
        b1[i] = b1[i + 1]^a[i];
    }
    int mx = b[1], mn = b[1];
    lmax[1] = mx, lmin[1] = b[1];
    insert(b[1], lch, lidx);
    for(int i = 2; i <= n; i++){
        mx = max(mx, query(b[i], lch));
        lmax[i] = mx;
        mn = min(mn, querym(b[i], lch));
        lmin[i] = mn;
        insert(b[i], lch, lidx);
    }
    mx = b1[n], mn = b1[n];
    rmax[n] = b1[n], rmin[n] = b1[n];
    insert(b1[n], rch, ridx);
    for(int i = n - 1; i >= 1; i--){
        mx = max(mx, query(b1[i], rch));
        rmax[i] = mx;
        mn = min(mn, querym(b1[i], rch));
        rmin[i] = mn;
        insert(b1[i], rch, ridx);
    }
    int ans = 0;
    for(int i = 1; i <= n; i++){
        if(i != n) ans = max(ans, lmax[i] - rmin[i + 1]);
        if(i != 1) ans = max(ans, rmax[i] - lmin[i - 1]);
    }
    cout << ans << endl;
}

signed main(){
    ios; int _;
    _ = 1; //cin >> _;
    while(_--){
        solve();
    }
    return 0;
}
  • 17
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值