Perfect Security CodeForces - 948D 01字典树解决XOR最值问题

题意:

给一个整数数组A 和一个整数数组P 求A与P的某个排列的异或的最小字典序数列

转化一下 其实就是从A1开始 每个数在P中求一个对应的异或的最小值 那就可以把P插入一棵01字典树中 然后用A去查找那棵树的最小值

其实关于XOR的最值问题很多都应该用01字典树去解决 这题是一个模板题

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <bitset>
#include <vector>
#include <string>
#include <deque>
#include <list>
#include <set>
#include <map>
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;

typedef long long ll;
const int maxn=3000005;

int n,rt=1;
int T[maxn*3][2],v[maxn*3],A[maxn],num[maxn*3],B[maxn];

inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

void Insert(int x,int id)
{
    int u=0,op;
    for(int i=30;i>=0;i--)
    {
        op=((x&(1<<i))!=0);
        if(!T[u][op]) T[u][op]=rt++;
        u=T[u][op];
        num[u]++;
    }
    v[u]=id;
}

void del(int x)
{
    int u=0,op;
    for(int i=30;i>=0;i--)
    {
        op=((x&(1<<i))!=0);
        u=T[u][op];
        num[u]--;
    }
}

int get(int x)
{
    int u=0,op;
    for(int i=30;i>=0;i--)
    {
        op=((x&(1<<i))!=0);
        if(T[u][op]&&num[T[u][op]]) u=T[u][op];
        else u=T[u][op^1];
    }
    del(A[v[u]]);
    return x^A[v[u]];
}
int main()
{
    n=read();
    for(int i=1;i<=n;i++) B[i]=read();
    for(int i=1;i<=n;i++) Insert(A[i]=read(),i);
    for(int i=1;i<=n;i++) printf("%d ",get(B[i]));
    return 0;
}

关于01字典树解决xor问题可以详见这篇博客:

https://blog.csdn.net/guhaiteng/article/details/52191831

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值