当前位置: 首页 > 工具软件 > Lever > 使用案例 >

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

公西英叡
2023-12-01

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;
}
 类似资料: