HDU2578_Dating with girls(1)(二分)

来源:互联网 发布:整理通讯录的软件 编辑:程序博客网 时间:2024/05/16 09:05

Dating with girls(1)

Time Limit: 6000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2937    Accepted Submission(s): 908


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
25 41 2 3 4 58 81 4 5 7 8 9 2 6
 

Sample Output
35
 

Source
HDU 2009-5 Programming Contest
 

Recommend
lcy
 

解题报告
二分。。。
注意可能有这样的数据1 1 1 2 3,答案是3
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int num[100010];int bin(int key,int n){    int l=0,r=n-1,mid;    while(l<=r)    {        mid=(l+r)/2;        if(num[mid]<key)            l=mid+1;        else if(num[mid]>key)            r=mid-1;        else        {            return 1;        }    }    return 0;}int main(){    int t,i,j,n,k;    scanf("%d",&t);    while(t--)    {        memset(num,0,sizeof(num));        int cnt=0;        scanf("%d%d",&n,&k);        for(i=0; i<n; i++)            scanf("%d",&num[i]);        sort(num,num+n);        for(i=0; i<n; i++)        {            if(bin(k-num[i],n))            {                cnt++;                if(i!=0&&num[i-1]==num[i])                    cnt--;            }        }        printf("%d\n",cnt);    }    return 0;}



0 0
原创粉丝点击