题目链接
解题报告:
先任取一个数,会发现在比它小的数的二进制最高位为1且对应的较大数的这一位为
0
0
0,那么这两个数异或结果一定会变大。例如 ,
4
4
4 的二进制是
100
100
100,
1
1
1 的二进制是
1
1
1,
2
2
2 的二进制
10
10
10,
3
3
3 的二进制是
11
11
11 这几个数与
100
100
100 异或都会变大。那么对于这个问题我们只需要先把给定的数排序,然后从下到大逐个选取一个数,然后检查一个比这个数小的数且符合前文我们说的条件的数的个数。
代码展示:
#include<bits/stdc++.h>
#define LL long long
#define pii pair<int,int>
#define all(x) x.begin(),x.end()
#define mem(a, b) memset(a,b,sizeof(a))
using namespace std;
const int maxn = 2e5 + 5;
const int MOD = 1e9 + 7;
inline int read() {
int s = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {if (ch == '-') f = -1; ch = getchar();}
while (ch >= '0' && ch <= '9') {s = (s << 1) + (s << 3) + ch - '0'; ch = getchar();}
return s * f;
}
inline void write(LL x) {
if (x < 0) x = -x, putchar('-');
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
int a[maxn], b[35], c[35];
int main() {
int T = read(), n;
while (T--) {
mem(c, 0);
n = read();
int ans = 0;
for (int i = 1; i <= n; i++) a[i] = read();
sort(a + 1, a + n + 1);
for (int i = 1; i <= n; i++) {
bool flag = false;
for (int j = 30; j >= 0; j--) {
if ((a[i] >> j) & 1) (flag == false) ? c[j]++ : c[j], flag = true;
else if (flag) ans += c[j];
}
}
write(ans);
putchar('\n');
}
return 0;
}