思路:先把所有数字存进字典树,然后从最高位贪心。
代码:
#include<set> #include<map> #include<stack> #include<cmath> #include<queue> #include<vector> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> typedef long long ll; const int maxn = 100000 + 10; const int seed = 131; const ll MOD = 1e9 + 7; const ll INF = 1e17; using namespace std; int ch[32 * maxn][2], tot; ll val[32 * maxn]; void init(){ tot = 1; memset(ch[0], 0, sizeof(ch[0])); } void Insert(ll x){ int root = 0; for(int i = 31; i >= 0; i--){ int u = (x >> i) & 1; if(ch[root][u] == 0){ memset(ch[tot], 0, sizeof(ch[root])); ch[root][u] = tot++; } root = ch[root][u]; } val[root] = x; } ll query(ll x){ int root = 0; for(int i = 31; i >= 0; i--){ int u = (x >> i) & 1; if(ch[root][!u] != 0){ root = ch[root][!u]; } else root = ch[root][u]; } return val[root]; } int main(){ int T, Case = 1; scanf("%d", &T); while(T--){ init(); int n, m; scanf("%d%d", &n, &m); for(int i = 0; i < n; i++){ ll x; scanf("%lld", &x); Insert(x); } printf("Case #%d:\n", Case++); while(m--){ ll x; scanf("%lld", &x); printf("%lld\n", query(x)); } } return 0; }
原文地址:https://www.cnblogs.com/KirinSB/p/9827658.html
时间: 2024-10-08 22:53:17