ZOJ-3870 Team Formation(位运算)

来源:互联网 发布:韩国人种相貌 知乎 编辑:程序博客网 时间:2024/05/19 03:16
Team Formation

Time Limit: 2 Seconds      Memory Limit: 131072 KB

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{AB}).

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 contains N positive integers separated by spaces. The ith integer denotes the skill level of ith student. Every integer will not exceed 109.

Output

For each case, print the answer in one line.

Sample Input

231 2 351 2 3 4 5

Sample Output

16

Author: LIN, Xi

Source: The 12th Zhejiang Provincial Collegiate Programming Contest

题意:给你n个人的值,让你找有多少组不同的team,这个team要求两个人,且两个人异或后的结果比两个人的值都大。

思路:

如果比两个数都大

那么对于一个数x来说,如果x的第i位0能找到对应的y在第i位是1,且是其最高位,那么x与y则是一个team了。

例如

====0==

00001==

所先预处理出有多少a[t]最高位在i位置就行啦

#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int N = 1e5+5;int a[N],num[N];void Cal(int x){    int l = 31;    while(l-- >= 0)    {        if(x & (1 << l))//计数,有多少数的最高位在位置L        {            num[l]++;            return;        }    }}int main(){    int t,n;    cin>>t;    while(t--)    {        memset(num,0,sizeof(num));        scanf("%d",&n);        for(int i = 1;i <= n;i++)        {            scanf("%d",&a[i]);            Cal(a[i]);        }        int ans = 0;        for(int i = 1;i <= n;i++)        {            int l = 31;            while(l-- >= 0)//            {                if(a[i] & (1 << l))//找到a[i]的第一位即最高位                    break;            }            while(l-- >= 0)//找到a[i]的0位,这时候与最高位在此处的数异或肯定大于a[i]            {                if((a[i] & (1 << l)) == 0)                    ans += num[l];            }        }        printf("%d\n",ans);    }    return 0;}


1 0
原创粉丝点击