Codeforces Round #672 (Div. 2) B. Rock and Lever

B. Rock and Lever
Description

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 1≤t≤10 1t10) 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 ≤ 1 0 5 1≤n≤10^5 1n105) — length of the array.

The second line contains n positive integers ai ( 1 ≤ a i ≤ 1 0 9 1≤ai≤10^9 1ai109) — 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.

Example
input
5
5
1 4 3 7 10
3
1 1 1
4
6 2 5 3
2
2 4
1
1
output
1
3
2
0
0
Note

In the first test case there is only one pair: (4,7): for it 4 & 7=4, and 4⊕7=3.

In the second test case all pairs are good.

In the third test case there are two pairs: (6,5) and (2,3).

In the fourth test case there are no good pairs.

题意: 输入t 组测试数据,每组分两行,第一行输入n,第二行输入一个数组长度为n的数组数据。求这些数中有几对数的二进制与是大于等于二进制异或的,并输出结果。

题解: 用常规思路解题直接在第二个测试数据那里TLE,后来去看了看别人的博客,利用二进制最高位解题。如果两个数的二进制最高位相同,那么这两个数的逻辑与运算的结果一定大于逻辑异或运算的结果。

c++ AC 代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;

typedef long long ll;
const int maxn = 1e5 + 7;
const int mod = 1e9 + 7;

int a[maxn];
int sum[40];
int main()
{
	int T;
	scanf("%d", &T);
	while (T--)
	{
		memset(sum, 0, sizeof(sum));
		int n;
		scanf("%d", &n);
		ll ans = 0;
		for (int i = 1; i <= n; i++)
		{
			scanf("%d", &a[i]);
			int pos = 0;
			for (int j = 30; j >= 0; j--)
			{
				if (a[i] & (1 << j))
				{
					pos = j;
					break;
				}
			}
			ans += sum[pos];
			sum[pos]++;
		}
		printf("%lld\n", ans);
	}
	// system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值