[Zhengqing] [1893] 985's Math Challenge

Problem Description

985的数学难题
Time limit: 2 SecMemory limit: 128 MB

Description

985 has n positive integers, and he wants to quickly know the return value of the following function.

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
int a[N+1];
long long Solve() {
    int i, j;
    long long ans = 0;
    for(i = 1; i <= N; i++) {
    for(int j = i + 1; j <= N; j++) {
   ans += a[i] + a[j] + (a[i] ^ a[j]) + (a[i] | a[j]) + (a[i] & a[j]);
}
    }
    return ans;
}  

Note: ^ denotes the XOR operation.

Input

The first line contains an integer t, representing t test cases.
For each test case, the first line contains an integer representing the number of elements, and the next line contains n positive integers a[].
Note: 1 <= t <= 30, 1 <= n, a[] <= 100000.

Output

An integer representing the final return value ans.

Sample Input

1
2
3
4
5
2
1
10
2
1 1

Sample Output

1
2
0
4

Problem Analysis

Obviously, the function cannot be computed directly.
This type of problem involves binary operations.
There is a theorem:
x^y+x&y==x|y
Consider the effect of each bit of the binary representation on the result.
For example, apply the above operations to 1101, 1001, and 1010.
Then we can find that
the number of 1s in each bit from right to left is recorded as
cnt[0]~cnt[3] are respectively
2, 1, 1, 3
Because for the OR operation, except 0|0==0
all others are 1.
That is, 0|1+1|1
So for the rightmost bit, the number of effective 1s after the operation
is cnt[0](n-cnt[0])+(cnt[0](cnt[0]-1))/2
And the number represented by these 1s must be converted to decimal
so it must be multiplied by its corresponding 1«0
So the core code is

cpp
1
2
3
for(int i=0; i<lx; i++) {
	res+=(1<<i)*(cnt[0][i]*cnt[1][i]+(cnt[1][i]-1)*cnt[1][i]/2);
}

where lx represents the number of bits in the binary representation of the largest number.
As for computing a[i]+a[j]
we only need to sum a[1~n] and then multiply by (n-1).
That is, each number is used n-1 times.

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
long long a[100200];
int main() {
	int T;
	scanf("%d",&T);
	while(T--) {
		int n;
		scanf("%d",&n);
		for(int i=0; i<n; i++) {
			scanf("%d",&a[i]);
		}
		sort(a,a+n);
		long long cnt[2][50];
		int lx=0;
		memset(cnt,0,sizeof(cnt));
		for(; a[n-1]>>lx!=0; lx++)
			for(int i=0; i<n; i++)
				cnt[a[i]>>lx&1][lx]++;
		long long res=0;
		for(int i=0; i<lx; i++) {
			res+=(1<<i)*(cnt[0][i]*cnt[1][i]+(cnt[1][i]-1)*cnt[1][i]/2);
		}
		res*=2;
		for(int i=0; i<n; i++) {
			res+=(n-1)*a[i];
		}
		printf("%lld\n",res);
	}
	return 0;
}

Problem URL: ZZULI 1893 985’s Math Problem

Loading...