Dating with girls(1)

Problem 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!
Dating with girls(1)_第1张图片

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
思路:排序+二分查找
AC代码:
#include<iostream>
#include<algorithm>
#include<string.h>
#define N 100005
using namespace std;
int a[N],c[N];
int main()
{ int Case;
   cin>>Case;
   while(Case--)
   {   int n,k;
        int num=0,s=0;
         cin>>n>>k;
         for(int i=0;i<n;++i)
          cin>>c[i];
          sort(c,c+n);
          memset(a,0,sizeof(a));
          for(int i=0;i<n;++i)
            if(c[i]!=c[i+1])
            a[num++]=c[i];
            for(int j=0;j<num;++j)
            {  int low=0;
               int hig=num-1;
               while(low<=hig)
               {   int mid=(low+hig)/2;
                   if(a[j]+a[mid]==k)
                   { s++;
                     break;
                   }
                   else if(a[j]+a[mid]>k)
                         hig=mid-1;
                   else   low=mid+1;
               }
            }
            cout<<s<<endl;
   } return 0;
}


你可能感兴趣的:(Date,Integer,less,each,output,Numbers)