HDU2578: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!
 

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
 


 

思路:给出n个数,要找出其中任意两个和为K的对数

也就是X+Y中X和Y的位置不同也算不同

思路:排序加二分

 

#include <stdio.h>
#include <algorithm>
using namespace std;

int a[100005];

int bin(int x,int n)//二分
{
    int l,h,m;
    l = 0;
    h = n-1;
    m = (l+h/2);
    while(l<=h)
    {
        m = (l+h)/2;
        if(x<a[m])
            h = m-1;
        else if(x>a[m])
            l = m+1;
        else
            return 1;
    }
    return 0;
}

int main()
{
    int i,ans,n,k,t;
    scanf("%d",&t);
    while(t--)
    {
        int flag = 1;
        scanf("%d%d",&n,&k);
        ans = 0;
        for(i = 0; i<n; i++)
            scanf("%d",&a[i]);
        sort(a,a+n);
        for(i = 0; i<n; i++)
        {
            if(bin(k-a[i],n))
            {
                ans++;
                if(i!=0 && a[i] == a[i-1])//数字相同的要减去
                ans--;
            }
        }
        printf("%d\n",ans);
    }
}


 

你可能感兴趣的:(ACM,HDU,解题报告)