异或求和式
给定长度为n的序列A[i],求所有A[i] xor A[j] (i<j)的值之和
输入
第一行一个整数N
接下来N行,第i行为A[i]
输出
所需的值
样例输入
3
7
3
5
样例输出
12
样例解释
7 xor 3+3 xor 5+7 xor 5 = 4+6+2 = 12
先把数字都化成二进制,7:111, 3:011, 5:101,注意到异或具有交换律,也就是说只要能够使得任意两个数字都异或一次,就没有必要每次用前面的数字异或后面的数字。这启发我们不关注异或的顺序,而是关注结果。
易知:a个1,b个0两两异或的结果肯定是a*b个1,其余都是0。
三个数字的最低位分别是1,1,1,也就是三个1。那么最低位异或的结果一定是零个1,三个0,相加为0。
次低位分别是1,1,0,也就是两个1一个0。那么次低位异或的结果一定是两个1,一个0,相加为2。
最高位分别是1,0,1,也就是两个1一个0。那么最高位异或的结果一定是两个1,一个0,相加为2。
所以最后的答案应该是
代码如下:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
typedef long long int ll;
const int MAX_SIZE = 100;
int dp[MAX_SIZE], n;
int main()
{
//freopen("test.txt", "r", stdin);
scanf("%d", &n);
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; i++)
{
int t;
scanf("%d", &t);
int cnt = 0;
while (t)
{
cnt++;
if (t % 2)
dp[cnt]++;
t /= 2;
}
}
int ans = 0;
for (int i = 0; i < 31; i++)
ans += (1 << i) * dp[i + 1] * (n - dp[i + 1]);
printf("%d\n", ans);
return 0;
}