Description
给定n个非负整数A[1], A[2], ……, A[n]。
对于每对(i, j)满足1 <= i < j <= n,得到一个新的数A[i] xor A[j],这样共有n*(n-1)/2个新的数。求这些数(不包含A[i])中前k小的数。
注:xor对应于pascal中的“xor”,C++中的“^”。
对于100%的数据,2 <= n <= 100000; 1 <= k <= min{250000, n*(n-1)/2};
0 <= A[i] < 2^31
Solution
直到英语剧都演完了还没想出来
一个直观的想法就是按位贪心,我们只需要开一棵字典树把所有数字插入就能logn统计第k异或小。同时记录第i个数当前第id小的答案,每次取堆顶然后id++即可,非要说的话比较类似那个超级钢琴
需要注意的是数对(x,y)的贡献x^y只应该被算一次但是会被算两次,因此每弹栈两次才输出一次答案
Code
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define drp(i,st,ed) for (int i=st;i>=ed;--i)
const int N=100005;
int rec[N*40][2],size[N*40],tot=1;
int a[N];
struct data {
int x,ans,id;
bool operator <(data b) const {
return ans>b.ans;
}
} ;
std:: priority_queue <data> heap;
int read() {
int x=0,v=1; char ch=getchar();
for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
return x*v;
}
void ins(int x) {
int now=1;
drp(i,30,0) {
int ch=(x&(1<<i))!=0;
if (!rec[now][ch]) {
rec[now][ch]=++tot;
}
now=rec[now][ch];
size[now]++;
}
}
int ask(int x,int k) {
int now=1,ret=0;
drp(i,30,0) {
int ch=(x&(1<<i))!=0;
if (size[rec[now][ch]]<k||!rec[now][ch]) {
k-=size[rec[now][ch]];
ch=!ch; ret+=1<<i;
}
now=rec[now][ch];
}
return ret;
}
int main(void) {
int n=read(),m=read();
rep(i,1,n) {
a[i]=read();
ins(a[i]);
}
rep(i,1,n) {
int tmp=ask(a[i],2);
heap.push((data){a[i],tmp,2});
}
for (int i=1;i<m*2;i++) {
data top=heap.top(); heap.pop();
if (i&1) printf("%d ", top.ans);
if (top.id==n) continue;
int tmp=ask(top.x,++top.id);
heap.push((data) {top.x,tmp,top.id});
}
return 0;
}
/*
001
001
011
100
*/