For an upcoming programming contest, Edward, the headmaster of Marjar University, is forming a two-man team from N students of his university.
Edward knows the skill level of each student. He has found that if two students with skill level A 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.
There are multiple test cases. The first line of input contains an integer Tindicating 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 contains N positive integers separated by spaces. The ithinteger denotes the skill level of ith student. Every integer will not exceed 109.
For each case, print the answer in one line.
2 3 1 2 3 5 1 2 3 4 5
1 6阔怕的二进制
题意就是问你有几组a[i]^a[j] >max(a[i],a[j])(异或)
我们至于要想一下下什么时候才会出现大的情况呢。。
0000 1001
0001 0000
这样是大的 0001 1001
0001 1001
0001 0101
ans:0000 1100
这样结果变小
通过两组样例我们以得出只要最大的哪个一的位置不同
异或出的结果值一定是增大的。。、
所以我们用一个bits[]数组存储我们每个数最大值的位置
就好比 1001
bit【3】++;
就是这个道理
1
bit【0】++;
给出 10100
ans+=bit[3]+bit[1]+bit[0];
给出 1100
ans+=bit【1】+bit【0】;
就是这个道理了。。
当然了我们还可以存储0的位置直接乘ans+=(a[i]*bis[i])
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[1000003];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n;
scanf("%d",&n);
int bit[33]= {0};
for(int i=0; i<n; i++)
{
scanf("%d",&a[i]);
for(int j=31; j>=0; j--)
{
if(a[i]&(1<<j))
{
bit[j]++;
break;
}
}
}
int ans=0;
for(int i=0; i<n; i++)
{
int tem=a[i];
if(a[i]==0)continue;
int l=0;
for(int j=31; j>=0; j--)
{
if(a[i]&(1<<j))
{
l=j;
break;
}
}
for(int j=l; j>=0; j--)
{
if(!(a[i]&(1<<j)))
{
ans+=bit[j];
}
}
}
printf("%d\n",ans);
}
}
直接乘呢思路也差不多。。
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
int a[40];
int b[40];
int main()
{
int t,n,x,m,num;
scanf("%d",&t);
while(t--)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&x);
num=0,m=0;
while(x)
{
if(x&1) m=num;
else a[num]++;
num++;
x>>=1;
}
b[m]++;
}
long long int sum=0;
for(int i=0;i<=32;i++)
{
sum+=a[i]*b[i];
}
printf("%lld\n",sum);
}
return 0;
}