2021-10-21Codeforces Round #672 (Div. 2)B. Rock and Lever

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] >= a[i] xor a[j]条件成立的总数。
满足a[i] & a[j] >= a[i] xor a[j]就是要满足a[i] 和a[j] 这两个数在二进制表示中的最高位要相同。
例如:
4 二进制表示0100
7 二进制表示0111

那么就可以提前进行预处理数组a.
a[ i ]表示二进制表示下第 i 位为1,其他位为0的数。
那么就可以存储每一个区间 [a[ i ],a [i + 1] )中的满足条件的数的个数
用组合数的公式可以推出每一个区间中满足条件的组合的个数a[ i ] * (a[ i ] - 1) / 2
再将每一个区间中组合的个数相加可得答案
代码

#include<bits/stdc++.h>
 
#define first fi
#define second sc
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int N = 35;
const LL mod = 1e9  + 10;
 
int T;
int n,m;
LL a[N],b[N];
 
void init(){
	a[0] = 1;
	for(int i = 1;i <= 32;i ++){
		a[i] = a[i - 1] * 2;
	}
}
 
int main(){
	init();
	scanf("%d",&T);
	while(T --)
	{
		memset(b,0,sizeof b);
		scanf("%d",&n);
		for(int i = 0;i < n;i ++){
			int t;
			scanf("%d",&t);
			for(int j = 0; j <= 32;j ++)
			{
				if(t >= a[j] && t < a[j + 1]){
					b[j] ++;
					break;
				} 
			}
		}
		LL ans = 0;
		for(int i = 0;i <= 32;i ++)
		{
			LL t = b[i];
			ans += t * (t - 1) / 2;
		}
		cout<<ans<<endl;
	}
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值