Team Formation     ZOJ - 3870 

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.

Input

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.

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

题目大意就是有t组数据,每行先输入一个数n,然后这n个数中两两组合,问有多少种组合符合 a^b > max(a,b) ,输出个数。

思路:因为是1e5的限制,直接开两个for循环肯定会超时,所以就要另寻他法了。先任取一个数,会发现在比它小的数的二进制最高位为1且对应的较大数的这一位为0,那么这两个数异或结果一定会变大。例如 ,4的二进制是100, 1的二进制是1,2的二进制10, 3的二进制是11 这几个数与100异或都会变大。那么对于这个问题我们只需要先把给定的数排序,然后从下到大逐个选取一个数,然后检查一个比这个数小的数且符合前文我们说的条件的数的个数。

code:

#include <cstdio> 
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long LL;
const int MAXN = (int) 1e5 + 7;

int a[MAXN];

int main()
{
	int t, n;
	int cnt[70];	// cnt[i]代表a数组都转换成二进制数后最高位所在位置i为1的数的个数
	int b[70];	// 保存一个转化为二进制的数 
	scanf("%d", &t);
	while(t--)
	{
		memset(a, 0, sizeof(a));
		memset(cnt, 0, sizeof(cnt));
		scanf("%d", &n);
		for(int i=0; i<n; i++)
		{
			scanf("%d", &a[i]);
		}
		sort(a, a+n);	// 先排序 
		int ans = 0;
		for(int i=0; i<n; i++)	// 从小到达逐个选取 
		{
			int j = 0;
			while(a[i])	// 把a[i]转化成二进制 
			{
				b[j++] = a[i] % 2;
				a[i] /= 2;
			} 
			for(int k=0; k<j; k++)	// 检查比这个数小的数的最高位 
			{
				if(b[k] == 0)		// 检查这个数对应的为时是否为0 
					ans += cnt[k]; 
			}
			cnt[j-1] ++;	// 保存当前这个数的最高位所在位置 
		}
		printf("%d\n", ans);
	}	
	
	
	
	
	return 0;
}