題目
輸入
輸出
Sample Input
3 5
1 8 13
7 5 4 8 3
Sample Output
7
數據範圍
解法
首先如果要x xor y=k中,k有僅有兩位是1的話。
那麼就:(x xor(2^i)) xor (y xor(2^j))=0。
則 x xor (2^i)=y xor (2^j)。
於是可以想到折半搜索。
先枚舉i,然後把x的異或值扔進hash裏面,再枚舉j,從hash裏找數量。
當然要減去i=j的情況。(方法很多,例如枚舉時強制i < j)。
代碼
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cmath>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define ll long long
using namespace std;
const int maxn=1e5+5,M=30,mo=23332333;
int n,m,a[maxn],b[maxn],er[M],pos;
ll ans;
struct cy{
int num,val;
}ha[mo+2];
int read()
{
int x=0;
char c;
for(c=getchar();c<'0'||c>'9';c=getchar());
for(c;c>='0'&&c<='9';c=getchar()) x=x*10+c-48;
return x;
}
void hash(int x)
{
pos=x%mo;
while (ha[pos].val!=0&&ha[pos].val!=x) pos=pos%mo+1;
ha[pos].val=x; ++ha[pos].num;
}
int getha(int x)
{
pos=x%mo;
while (ha[pos].val!=0&&ha[pos].val!=x) pos=pos%mo+1;
return ha[pos].num;
}
int main()
{
n=read(); m=read();
er[0]=1;
fo(i,1,M) er[i]=er[i-1]*2;
fo(i,1,n) {
a[i]=read();
int now=a[i]^er[0];
hash(now);
}
fo(i,1,m) b[i]=read();
fo(i,1,29){
fo(j,1,m){
int now=b[j]^er[i];
ans+=getha(now);
}
fo(j,1,n){
int now=a[j]^er[i];
hash(now);
}
}
printf("%lld\n",ans);
}