three arrays

题目链接

题意

打乱两个数列,对应位置异或产生一个新数列,使它字典序最小。

思路

建两棵字典树,然后尽量走他们相同的边,这样异或出的数字尽量小,排一下序,让最小的在前面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#ifndef ONLINE_JUDGE
#define dbg(x...) do{cout << "\033[33;1m" << #x << "->" ; err(x);} while (0)
void err(){cout << "\033[39;0m" << endl;}
template<template<typename...> class T, typename t, typename... A>
void err(T<t> a, A... x){for (auto v: a) cout << v << ' '; err(x...);}
template<typename T, typename... A>
void err(T a, A... x){cout << a << ' '; err(x...);}
#else
#define dbg(...)
#endif
#define inf 1ll << 50
const int N = 1e5 + 5;
const int maxn = N * 2 * 25;
int tot;
int ch[maxn][2];
int sum[maxn];
int root1, root2;

int newnode()
{
tot++;
for (int i = 0; i < 2; i++)
ch[tot][i] = 0;
sum[tot] = 0;
return tot;
}
void insert(int root, int x)
{
int cur = root;
for (int p = 29; p >= 0; p--)
{
int t = (x >> p) & 1;
int u = ch[cur][t];
if (!u)
{
ch[cur][t] = newnode();
u = ch[cur][t];
}
sum[cur]++;
cur = u;
}
sum[cur]++;
}
int ans[N];
int cnt;

inline bool exist(int u)
{
if (!u || sum[u] == 0)
return false;
return true;
}

int query(int u, int v, int tmp1, int tmp2)
{
if (!ch[u][0] && !ch[u][1])
{
int s = min(sum[u], sum[v]);
for (int i = 1; i <= min(sum[u], sum[v]); i++)
ans[++cnt] = tmp1 ^ tmp2;
sum[u] -= s;
sum[v] -= s;
//dbg(sum[u], sum[v], tmp1, tmp2);
return s;
}
int s = 0;
for (int i = 0; i < 2; i++)
{
if (exist(ch[u][i]) && exist(ch[v][i]))
{
//puts("same");
//dbg(tmp1, tmp2, i);
int t = query(ch[u][i], ch[v][i], tmp1 << 1 | i, tmp2 << 1 | (i));
sum[u] -= t;
sum[v] -= t;
s += t;
}
}
for (int i = 0; i < 2; i++)
{
if (exist(ch[u][i]) && exist(ch[v][!i]))
{
//puts("diff");
//dbg(tmp1, tmp2, i);
int t = query(ch[u][i], ch[v][!i], tmp1 << 1 | i, tmp2 << 1 | (!i));
sum[u] -= t;
sum[v] -= t;
s += t;
}
}
return s;
}
int a[N], b[N];
void init()
{
tot = 0;
root1 = newnode();
root2 = newnode();
cnt = 0;
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for (int i = 1; i <= n; i++)
scanf("%d", &b[i]);
init();
for (int i = 1; i <= n; i++)
insert(root1, a[i]);
for (int i = 1; i <= n; i++)
insert(root2, b[i]);
assert(query(root1, root2, 0, 0) == n);
sort(ans + 1, ans + n + 1);
for (int i = 1; i <= n; i++)
printf("%d%c", ans[i], i == n? '\n': ' ');
}
return 0;
}
0%