HDU 2578 Dating with girls(1)

来源:互联网 发布:网络管理与维护 王平安 编辑:程序博客网 时间:2024/04/28 16:52

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!
 

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

25 41 2 3 4 58 81 4 5 7 8 9 2 6
 

Sample Output

35

注意:去除数组中重复的数,因为重复的数只用一次。

代码如下:

#include<stdio.h>#include<algorithm>using namespace std;int binary(int a[],int i,int n,int k){    int low=i+1,high=n-1,mid;    while(low<=high)    {        mid=(low+high)/2;        if(a[i]+a[mid]>k)            high=mid-1;        else if(a[i]+a[mid]<k)            low=mid+1;        else            return(mid);    }    return(-1);}int main(){    int T,i,j,n,k,num,num1,a[100005];    scanf("%d",&T);    while(T--)    {        scanf("%d%d",&n,&k);        for(i=0;i<n;i++)            scanf("%d",&a[i]);        sort(a,a+n);        num=0;        num1=0;        for(i=0;i<n;i++)        {            if(a[i]==a[i+1])                continue;            if(k%2==0&&a[i]==k/2)                num1++;            if(binary(a,i,n,k)!=-1)                num++;        }        printf("%d\n",num*2+num1);    }}


0 0
原创粉丝点击