bzoj3689 异或之 字典树+堆

15 篇文章 0 订阅

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
*/
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值