Spoj-BITDIFF Bit Difference

Given an integer array of N integers, find the sum of bit differences in all the pairs that can be formed from array elements. Bit difference of a pair (x, y) is the count of different bits at the same positions in binary representations of x and y. For example, bit difference for 2 and 7 is 2. Binary representation of 2 is 010 and 7 is 111 (first and last bits differ in two numbers).

Input

Input begins with a line containing an integer T(1<=T<=100), denoting the number of test cases. Then T test cases follow. Each test case begins with a line containing an integer N(1<=N<=10000), denoting the number of integers in the array, followed by a line containing N space separated 32-bit integers.

Output

For each test case, output a single line in the format Case X: Y, where X denotes the test case number and Y denotes the sum of bit differences in all the pairs that can be formed from array elements modulo 10000007.

Example

Input:
1
4
3 2 1 4

Output:
Case 1: 22

求和:对任意一对数(a,b)二进制展开,这两个数有多少位是01不同的

把每一位拆开来,假设第i位是1的有bit[i]个,答案就是Σ2*bit[i]*(n-bit[i])

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<cstdlib>
 5 #include<algorithm>
 6 #include<cmath>
 7 #include<queue>
 8 #include<deque>
 9 #include<set>
10 #include<map>
11 #include<ctime>
12 #define LL long long
13 #define inf 0x7ffffff
14 #define pa pair<int,int>
15 #define mkp(a,b) make_pair(a,b)
16 #define pi 3.1415926535897932384626433832795028841971
17 #define mod 10000007
18 using namespace std;
19 inline LL read()
20 {
21     LL x=0,f=1;char ch=getchar();
22     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
23     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
24     return x*f;
25 }
26 int n;
27 LL ans;
28 int a[10010];
29 int bit[40];
30 inline void work(int cur)
31 {
32     n=read();
33     for (int i=1;i<=n;i++)a[i]=read();
34     ans=0;
35     memset(bit,0,sizeof(bit));
36     for (int i=1;i<=n;i++)
37         for (int j=0;j<=31;j++)
38         if (a[i] & (1<<j))bit[j]++;
39     for (int j=0;j<=31;j++)
40         ans+=(LL)bit[j]*(n-bit[j])*2;
41     printf("Case %d: %lld
",cur,ans%mod);
42 }
43 int main()
44 {
45     int T=read(),tt=0;
46     while (T--)work(++tt);
47 }
Spoj BITDIFF
原文地址:https://www.cnblogs.com/zhber/p/7153395.html