ZOJ3870(位运算与思维)

来源:互联网 发布:手机幻灯片制作软件 编辑:程序博客网 时间:2024/04/29 01:20


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 AB, 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.AB > 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

231 2 351 2 3 4 5

Sample Output

16

题目大意 : 就是给你N个数,找寻其中的两个数使得这两个数的异或值大于这两个数中的任意一个的情况数。

解题思路 : 正常的时候应该两两计算异或值判断,复杂度为O(n^2),但是因为题目的数据量比较大为10^6,会超时随意不可行。 那怎么办呢,。 既然题目说的是异或,那么就是位运算,那么就在二进制上思考。 题目要的又是异或的值大于这两个值的每一个 也就是满足大于这两个数中大的一个即可 , 那么就想一想仅在二进制下,两个数怎么比较大小。 我们知道二进制下的值 换算成10进制就是 2的整数次幂加和的形式 example: x = 100001110(2) = 2^8+2^3+2^2+2^1; y = 100011010(2) = 2^8+2^4+2^3+2^1; 看等式右边很容易就能得出 x < y; 从最高位看是比较 如果相同就比较下一位,知道出现不同的情况 ,如果不同即一为0一为1 , 则这位为1的大,这时候后面的位数如何变化都不重要了,变化的这一位在数值上已经比后面的位数最大的情况还要大了,所以不需要考虑;

知道这些在异或 二进制下 同位运算 相异为1 (0^1/1^0) 相同为0 (1^1/0^0)

一个数在异或运算之后要比本身大,需要的是其与其异或运算的数在最高位(不计算前导0)的位上为0; 解释一下: 100001110 想要得到一个比它大的一个数只需要在它为0的任意1位上变为1即可(这时需要在这位的前面的任何一位都不改变,而后面的值则无所谓,前文已经解释) 所以另1个数的最高为在这个数为0的位上即可

明白了以上几点,本题就可以做了, 首先要把每个数的二进制上的为0的位数都记录下来(前导0不算) 在把每个数在二进制上的最高位(必为1)记录下来 比如说在二进制上的某一位 存在在这位上为0的数为n个,存在最高位在这位上的数为m个 则满足题目的结果就为n*m个;

而题目的数据为最大10^9 那么在二进制上就不超过int整形 既是32位; 所以只需要计算这32位的的情况的和即可

把每位的情况分别用两个数组来存就行。

代码:

#include <stdio.h>#include <stdlib.h>#include <algorithm>#include <string.h>#include <queue>#include <iostream>using namespace std;int a[100],b[100];int main(){    int t,g,k;    while(cin>>t)    {        while(t--)        {            cin>>g;            memset(a,0,sizeof(a));            memset(b,0,sizeof(b));            for(int i=0; i<g; i++)            {                cin>>k;                int x,y;                x=y=0;                while(k)                {                    if(k&1)                        x=y;                    else                        a[y]++;                    y++;                    k>>=1;                }                b[x]++;            }            int sum=0;            for(int i=0; i<32; i++)            {                sum+=a[i]*b[i];            }            cout<<sum<<endl;        }    }}

0 0
原创粉丝点击