CodeForces - 923C

· · 个人记录

题意

有长度为 n 的数列 a,b,将数列 b 重新排列,使得数列 c 字典序最小,c_i = a_i \oplus b_i(1 \le i \le n)。

思路

可以使用贪心。

对于给定的 b 数组,建立字典树。接着对于每个 a_i (1 \le i \le n),在字典树上贪心选择,同时把访问的数删除。

代码

#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll read(){ ll x = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-'){ f = -1; } ch = getchar(); } while(ch >= '0' && ch <= '9'){ x = x * 10 + ch - '0', ch = getchar(); } return x * f; }
void write(ll x) { if(x < 0){ putchar('-'), x = -x; } if(x > 9){ write(x / 10); } putchar(x % 10 + '0'); }

const int N = 3e5 + 3;
int n, a[N], p[N];

struct trie{
    int t[N * 32][2], tc;
    int s[N * 32];

    void change(int x){
        int p = 0;
        for(int i = 31; i >= 0; i --){
            int w = (x >> i) & 1;
            if(!t[p][w]) t[p][w] = ++ tc;
            p = t[p][w];
            s[p] ++;
        }
    }

    int Find(int x){
        int p = 0, ans = 0;
        for(int i = 31; i >= 0; i --){
            int w = (x >> i) & 1;
            if(t[p][w] && s[t[p][w]]) p = t[p][w];
            else if(t[p][w ^ 1] && s[t[p][w ^ 1]]) p = t[p][w ^ 1], ans |= (1 << i);
            s[p] --;
        }
        return ans;
    }
}t;

int main(){

    n = read();
    for(int i = 1; i <= n; i ++){
        a[i] = read();
    }
    for(int i = 1; i <= n; i ++){
        p[i] = read();
        t.change(p[i]);
    }

    for(int i = 1; i <= n; i ++){
        write(t.Find(a[i])), putchar(' ');
    }

    return 0;
}