For an upcoming programming contest, Edward, the headmaster of Marjar University, is forming a two-man team fromN students of his university.
Edward knows the skill level of each student. He has found that if two students with skill levelA and B form a team, the skill level of the team will be A ⊕ B, where ⊕ means bitwise exclusive or. A team will play well if and only if the skill level of the team is greater than the skill level of each team member (i.e.A ⊕ B > max{A, B}).
Edward wants to form a team that will play well in the contest. Please tell him the possible number of such teams. Two teams are considered different if there is at least one different team member.
Input
There are multiple test cases. The first line of input contains an integer T indicating the number of test cases. For each test case:
The first line contains an integer N (2 <= N <= 100000), which indicates the number of student. The next line containsN positive integers separated by spaces. The ith integer denotes the skill level ofith student. Every integer will not exceed 109.
Output
For each case, print the answer in one line.
Sample Input
2 3 1 2 3 5 1 2 3 4 5
Sample Output
1 6
打表找规律即可:规律:只要一个人能与m个人组成一个m个不同的队那么与这个人的值的二进制位数相同的人也能与相同的m个人组队
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn=100010;
struct Node{
int num;
int cnt;
int ans;
}A[maxn];
int vis[maxn];
bool cmp(Node a,Node b){
if(a.cnt==b.cnt)
return a.num<b.num;
return a.cnt<b.cnt;
}
int main()
{
int t,n,i,j,k;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(i=0;i<n;++i){
scanf("%d",&A[i].num);
int m=A[i].num;A[i].cnt=0;
while(m){
m/=2;
A[i].cnt++;
}
}
memset(vis,0,sizeof(vis));
sort(A,A+n,cmp);
int ans=0;
for(k=0;k<n;++k){
if(k&&A[k].cnt==A[k-1].cnt){
ans+=A[k-1].ans;
A[k].ans=A[k-1].ans;
continue;
}
A[k].ans=0;
for(i=k+1;i<n;++i){
if((A[k].num^A[i].num)>max(A[k].num,A[i].num))A[k].ans++;
}
ans+=A[k].ans;
}
printf("%d\n",ans);
}
return 0;
}
2016年5月1日更新
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<list>
#include<queue>
#include<vector>
using namespace std;
const int maxn=1000010;
/*
思路 当位数相同时一定不可以当位数不同时如果可以则位数均可
*/
struct Node{
int num,cnt;
}A[maxn];
int bit[35];
int main()
{
int t,n,k,cnt;
scanf("%lld",&t);
while(t--){
scanf("%d",&n);
memset(bit,0,sizeof(bit));
for(int i=1;i<=n;++i){
scanf("%d",&A[i].num);
int temp=A[i].num,cnt=0;
while(temp){temp/=2;cnt++;}
bit[cnt]++;A[i].cnt=cnt;
}
long long ans=0;
for(int i=1;i<=n;++i){
for(int j=A[i].cnt-1;j>=1;--j){
if((A[i].num^(1<<(j-1)))>A[i].num)ans+=bit[j];
}
}
printf("%lld\n",ans);
}
return 0;
}