EXPOR - OR
Given an array of N integers A1, A2, A3…AN. If you randomly choose two indexes i ,j such that 1 ≤ i < j ≤ N, what is the expected value of Ai | Aj?
Input
First line contains an integer T, the number of test cases. Each test case consists of two lines. First line denotes the size of array, N and second line contains N integers forming the array.
1 ≤ T ≤ 10
2 ≤ N ≤ 100,000
0 ≤ Ai < 231
Output
For each test case, print the answer as an irreducible fraction. Follow the format of the sample output.
The fraction p/q (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1 that divides both p and q separately.
Example
Input: 2 2 0 0 3 1 2 3 Output: 0/1 3/1
思路:根据按位与的性质,考虑每个数对答案的贡献即可,用前缀和存下每个二进制位可以搞定。
# include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
int s[33];
ull gcd(ull a, ull b)
{
return b==0?a:gcd(b, a%b);
}
int main()
{
int t, n, m;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
memset(s, 0, sizeof(s));
ull ans = 0;
for(int i=1; i<=n; ++i)
{
scanf("%d",&m);
for(int j=0; j<32; ++j)
{
int tmp = (m>>j)&1;
if(tmp)
ans = ans + (ull)(i-1)*(1<<j);
else
ans = ans + (ull)s[j]*(1<<j);
s[j] += tmp;
}
}
ull g = gcd(ans, (ull)n*(n-1)/2);
printf("%llu/%llu\n",ans/g, (ull)n*(n-1)/2/g);
}
return 0;
}