CF742B Arpa's obvious problem and Mehrdad's terrible solution 题解
Content
有一个长度为 \(n\) 的数组,请求出使得 \(a_i \oplus a_j=x\) 且 \(i\neq j\) 的数对 \((i,j)\) 的个数。其中 \(\oplus\) 表示异或符号。
数据范围:\(1\leqslant n,a_i\leqslant 10^5,0\leqslant x\leqslant 10^5\)。
Solution
利用一个异或的性质:\(a\oplus b=c\Rightarrow a\oplus c=b,b\oplus c=a\),我们发现问题其实就迎刃而解了。直接统计每个数异或 \(x\) 得到的数在原数组里面的个数再加起来就好了。
注意,数对可能很多,要开 \(\texttt{long long}\)。
Code
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
#include <map>
using namespace std;
int n, x, a[100007];
map<int, int> vis;
long long ans;
int main() {
scanf("%d%d", &n, &x);
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
ans += vis[a[i] ^ x];
vis[a[i]]++;
}
printf("%d", ans / 2);
return 0;
}