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?
Each test contains multiple test cases.
The first line contains one positive integer t ( 1 ≤ t ≤ 10 1≤t≤10 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 ≤ 1 0 5 1≤n≤10^5 1≤n≤105) — length of the array.
The second line contains n positive integers ai ( 1 ≤ a i ≤ 1 0 9 1≤ai≤10^9 1≤ai≤109) — elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 105.
For every test case print one non-negative integer — the answer to the problem.
5
5
1 4 3 7 10
3
1 1 1
4
6 2 5 3
2
2 4
1
1
1
3
2
0
0
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;
}