思路:使用一个0和1的二叉树存储所有二进数,输入一个存一个再找一次,不用全部存进去后再找。为了使异或值最大,每一次查找和输入的a每一位都不同的方向(如果有的话),最后返回查找值。
代码:
- #include
- #include
- #include
- #include
- using namespace std;
- const int N=3e6+10;
- int son[N][2],idx;
- int n;
- void insert(int x)
- {
- int p=0;
- for(int i=30;i>=0;i--)
- {
- int u=x>>i&1;
- if(!son[p][u]) son[p][u]=++idx;
- p=son[p][u];
- }
- }
- int que(int x)
- {
- int p=0,res=0;
- for(int i=30;i>=0;i--)
- {
- int u=x>>i&1;
- if(son[p][!u])
- {
- p=son[p][!u];
- res=res*2+!u;
- }else
- {
- p=son[p][u];
- res=res*2+u;
- }
- }
- return res;
- }
- int main()
- {
- cin>>n;
- int a;
- int res=0;
- for(int i=1;i<=n;i++)
- {
- cin>>a;
- insert(a);
- int t=que(a);
- res=max(res,a^t);
- }
- cout<
- return 0;
- }
在查询时异或,直接返回当前数字能够异或到的最大的值,不需要得到一个返回值后再异或一次
- #include
- #include
- #include
- #include
- using namespace std;
- typedef unsigned long long ull;
- const int N=3e6+10;
- int son[N][2],idx;
- int cnt[N];
- string s[10010];
- int flag;
- void insert(int a)
- {
- int p=0;
- for(int i=30;i>=0;i--)
- {
- int u=a>>i&1;
- if(!son[p][u]) son[p][u]=++idx;
- p=son[p][u];
- }
- }
- int que(int x)
- {
- int p=0,res=0;
- for(int i=30;i>=0;i--)
- {
- int u=x>>i&1;
- if(son[p][!u])
- {
- p=son[p][!u];
- res=res*2+1;
- }else
- {
- p=son[p][u];
- res=res*2;
- }
- }
- return res;
- }
- int main()
- {
- int n;
- scanf("%d",&n);
- int sum=0;
- for(int i=1;i<=n;i++)
- {
- int a;
- scanf("%d",&a);
- insert(a);
- int t=que(a);
- sum=max(sum,t);
- }
- cout<
- return 0;
- }
-
相关阅读:
进阶的风控策略篇:如果筛选最佳策略帮我们锁定优质客群
Spring Boot 2 :Spring Boot项目依赖(重点)&&连接Mysql(重点)
Linux下VSCode的安装和基本使用
基于Java毕业设计中小企业人力资源管理系统源码+系统+mysql+lw文档+部署软件
Linux命令(87)之pwd
JDY蓝牙注意事项
Centos8系统配置Redis实现开机自启
ArcGIS中的镶嵌数据集与接缝线
【LeetCode滑动窗口专题#2】无重复字符的最长子串
rhel7.0解决yum无法使用(system is not registered to Red Hat Subscription Management)
-
原文地址:https://blog.csdn.net/m0_62327332/article/details/126501522