Codeforces B. Rock and Lever

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;
	}
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

henulmh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值