一直找工作都很累,思维都跟不上了,题目也不是想不到方法,但是那天真的没写好,然后影响了做最后一个问题,不知道有没有面试的机会,还是很喜欢这个公司的。 不说废话了,补上代码。
就是输入n和m,代表输入n个数,求两两异或大于m的对数有多少?这个题目大概是知道应该是个nlogn左右的复杂度,想了一下遍历加二分,发现有点复杂,今天看到trie树维护,就感觉好写了,贴上代码。
<span style="font-size:18px;">#include <iostream>
using namespace std;
struct Trie{
int next[2];
int cnt;
Trie():cnt(1){next[0] = next[1] = -1;}
};
Trie trie[3500000];
int num[100001][18];
int len, n, m;
void insert(int *temp)
{
int pos = 0;
for(int i = 0; i <= 17; i ++){
if(trie[pos].next[temp[i]] == -1)
trie[pos].next[temp[i]] = len ++;
else
trie[pos].cnt ++;
pos = trie[pos].next[temp[i]];
}
}
int query(int *temp1, int *temp2)
{
int pos = 0, ans = 0;
for(int i = 0; i < 18; i ++){
if(pos == -1) break;
if(temp2[i] == 0){
ans += trie[ trie[pos].next[1 - temp1[i]] ].cnt;
pos = trie[pos].next[temp1[i]];
}
else{
pos = trie[pos].next[1 - temp1[i]];
}
}
return ans;
}
int main()
{
cin>>n>>m;
int val, temp[18];
len = 1;
for(int i = 0; i < n; i ++){
cin>>val;
for(int j = 17; j >=0; j -- ){
num[i][j] = val & 1;
val >>= 1;
}
insert(num[i]);
}
for(int i = 17; i >= 0; i --){
temp[i] = m & 1;
m >>= 1;
}
long long ans = 1;
for(int i = 0; i < n; i ++){
ans += query(num[i], temp);
}
cout<<ans/2<<endl;
return 0;
}</span>