Description
Everyone in the HDU knows that the number of boys is larger than the number of girls. But now, every boy wants to date with pretty girls. The girls like to date with the boys with higher IQ. In order to test the boys ' IQ, The girls
make a problem, and the boys who can solve the problem
correctly and cost less time can date with them.
The problem is that : give you n positive integers and an integer k. You need to calculate how many different solutions the equation x + y = k has . x and y must be among the given n integers. Two solutions are different if x0 != x1 or y0 != y1.
Now smart Acmers, solving the problem as soon as possible. So you can dating with pretty girls. How wonderful!

correctly and cost less time can date with them.
The problem is that : give you n positive integers and an integer k. You need to calculate how many different solutions the equation x + y = k has . x and y must be among the given n integers. Two solutions are different if x0 != x1 or y0 != y1.
Now smart Acmers, solving the problem as soon as possible. So you can dating with pretty girls. How wonderful!

Input
The first line contain an integer T. Then T cases followed. Each case begins with two integers n(2 <= n <= 100000) , k(0 <= k < 2^31). And then the next line contain n integers.
Output
For each cases,output the numbers of solutions to the equation.
Sample Input
2 5 4 1 2 3 4 5 8 8 1 4 5 7 8 9 2 6
Sample Output
3 5
解题思路
一组数要求其中两个数和为k的组合个数,a+b与b+a算两种(a=b时算一种);
二分查找,注意可能有重复数字
AC代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int cmp(const void*a, const void*b)
{
return *(int*)a-*(int*)b;
}
int main()
{
int T,h,n,k,i,j,move,cnt,a[100001],L,high,low,mid,flag;
scanf("%d",&T);
for(h=0;h<T;h++)
{
scanf("%d%d",&n,&k);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
qsort(a,n,sizeof(a[0]),cmp);
cnt=0;
flag=0;
for(i=0;i<n;i++)
{
if(a[i]==a[i-1]) //不需要特意去重,直接跳过即可;
continue;
if(a[i]>k/2) //剪枝,k/2后是重复查找
break;
if(a[i]==k/2 && k%2==0) //flag记录a=b && a+b=k 的有无
{
flag=1;
continue;
}
high=n; low=i;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid] < k-a[i])
low=mid+1;
else if( a[mid] > k-a[i] )
high=mid-1;
else
{
cnt++;
break;
}
}
}
printf("%d\n",cnt*2+flag);
}
return 0;
}