Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.
Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.
You are given a positive integer n, and an array a of positive integers. The task is to calculate the number of such pairs (i,j) that i<j and ai & aj≥ai⊕aj, where & denotes the bitwise AND operation, and ⊕ denotes the bitwise XOR operation.
Danik has solved this task. But can you solve it?
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1≤t≤10) denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains one positive integer n (1≤n≤105) — length of the array.
The second line contains n positive integers ai (1≤ai≤109) — elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 105.
Output
For every test case print one non-negative integer — the answer to the problem.
题意:给出一个数组a[i]~a[j],问有多少个(i,j),i<j,满足a[i]&a[j]>a[i]^a[j]
思路:仔细分析可以发现,只有当两个数的二进制的位数相等时,才有
a[i]&a[j] > a[i]^a[j]。因为只有这种情况,这两个数二进制的最高位的异或值为0且相与值为1。其余情况都是最高位相与为0,异或值为1。因此我们只需要对每一个数记录他之前有多少个数与它的二进制位数相等即可。然后全加起来就是答案。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
ll t,n,sum[100005],k,ans;
cin>>t;
while(t--)
{
cin>>n;
memset(sum,0,sizeof(sum)); //用sum[i]来记录在每个数之前二进制位数为i的数出现的次数
ans=0;
for(int i=1;i<=n;i++)
{
cin>>k;
int pos;
for(int j=30;j>=0;j--) //用来判断每一个k的二进制是几位
{
if(k & (1<<j)) //如果相与不为0了,说明当前j即为k的二进制位数
{
pos=j;
break;
}
}
ans+=sum[pos]; //由于当前数的二进制位数为pos,所以在他之前的数二进制位数为pos的都加上
sum[pos]++;
}
cout<<ans<<endl;
}
}