首页 技术 正文
技术 2022年11月9日
0 收藏 925 点赞 4,480 浏览 1193 个字

题意:给出A数组,B数组,你可以对A和B分别进行重排列,使得C[i]=A[i]^B[i]的字典序最小。

思路:对于这类题,显然需要建立字典树,然后某种形式取分治,或者贪心。  假设现在有了两颗字典树A,B,显然尽量让同方向的先匹配。

而且同一棵树的左右两边相互不影响,所以可以直接贪:如果A树上出发左走有x个数字,B左走有y个数字,那么一定会左匹配min(x,y);右匹配同理; 剩下的交叉匹配;

看代码应该就会看懂了:add建立字典树。

dfs进行匹配;  (i,j)从前往后分别是,(0,0) (1,1),(0,1) (1,0)保证了相同的先匹配。

#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int maxn=;
int ch0[maxn*][],ch1[maxn*][],tot0,tot1;
int ans[maxn],num,sum0[maxn*],sum1[maxn*];
void init()
{
rep(i,,tot0) rep(j,,) ch0[i][j]=;
rep(i,,tot1) rep(j,,) ch1[i][j]=;
tot0=tot1=num=;
}
void add(int ch[][],int sum[],int x,int &tot)
{
for(int i=,now=;i>=;i--){
int t=(x>>i)&;
if(!ch[now][t]) ch[now][t]=++tot;
now=ch[now][t];
sum[now]++;
}
}
void dfs(int now0,int now1,int cost,int dep)
{
int e=min(sum0[now0],sum1[now1]);
sum0[now0]-=e; sum1[now1]-=e;
if(dep==-) {
rep(i,,e) ans[++num]=cost;
return ;
}
rep(k,,){
int i=k&,j=i^; if(k<=) j=i;
if(sum0[ch0[now0][i]]&&sum1[ch1[now1][j]])
dfs(ch0[now0][i],ch1[now1][j],cost+(i==j?:(<<dep)),dep-);
}
}
int main()
{
int T,N,x;
scanf("%d",&T);
while(T--){
init();
scanf("%d",&N);
rep(i,,N){
scanf("%d",&x);
add(ch0,sum0,x,tot0);
}
rep(i,,N){
scanf("%d",&x);
add(ch1,sum1,x,tot1);
}
dfs(,,,);
sort(ans+,ans+N+);
rep(i,,N-) printf("%d ",ans[i]);
printf("%d\n",ans[N]);
}
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,498
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,136
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,300