hdu- 6625 three arrays 字典树 贪心

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6625

 

题意:

       现在你有一个长为n的数组a和数组b,现在要你把两个数组进行重新排序,排序后可以根据两个数组得到一个新的数组c  c[i]=a[i]^b[i],  现在请你重排a和b数组,使得得到的这个c的字典序最小,输出c数组。

做法:

       参考了大神的代码做法,对两个数组都构造字典树,优先走两个数组共同的部分再走不同的部分,高位优先走(仿佛是废话..),代码的处理很是简洁。

       反正做到的时候一脸懵啊...看到了大神的博客的做法觉得甚是神奇,我这个代码残只能默默的模仿大神的方便写法...(如果自己写肯定是120行起步的感觉...)。


#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=(int)a;i<=(int)b;i++)
using namespace std;
typedef long long ll;
const int maxn=100005*30;
const int maxm=100005;
struct Trie{
    int nex[maxn][2],num[maxn],cnt[maxn];
    int root,tot;
    int newcode(){
        memset(nex[tot],0,sizeof(nex[tot]));
        num[tot]=0; cnt[tot]=0;
        return tot++;
    }
    void init(){
        tot=0;
        root=newcode();
    }
    void Insert(int x){
        int rt=root;
        for(int i=29;i>=0;i--){
            int now=(x>>i&1);
            if(!nex[rt][now]) nex[rt][now]=newcode();
            rt=nex[rt][now];
            ++cnt[rt];
        }
        num[rt]++;
    }
} one,two;
vector<int> ans;
int n;
void dfs(int rt1,int rt2,int aim){
    int up=min(one.cnt[rt1],two.cnt[rt2]);
    one.cnt[rt1]-=up;
    two.cnt[rt2]-=up;
    if(one.num[rt1]){
        rep(i,1,up){
            ans.push_back(aim);
        }
        return ;
    }
    int on1=one.nex[rt1][1],on0=one.nex[rt1][0];
    int tw1=two.nex[rt2][1],tw0=two.nex[rt2][0];
    if(one.cnt[on1]&&two.cnt[tw1]) dfs(on1,tw1,aim*2);
    if(one.cnt[on0]&&two.cnt[tw0]) dfs(on0,tw0,aim*2);
    if(one.cnt[on1]&&two.cnt[tw0]) dfs(on1,tw0,aim*2+1);
    if(one.cnt[on0]&&two.cnt[tw1]) dfs(on0,tw1,aim*2+1);
}
int main(){
    int t; scanf("%d",&t);
    while(t--){
        one.init(); two.init();

        scanf("%d",&n);
        rep(i,1,n){
            int x; scanf("%d",&x);
            one.Insert(x);
        }
        rep(i,1,n){
            int x; scanf("%d",&x);
            two.Insert(x);
        }
        ans.clear();
        dfs(one.root,two.root,0);
        sort(ans.begin(),ans.end());
        rep(i,1,n){
            printf("%d%c",ans[i-1],i==n?'\n':' ');
        }
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值