hdu2578(二分法)

来源:互联网 发布:移动公司网络维修电话 编辑:程序博客网 时间:2024/06/06 05:17

Dating with girls(1)

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


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
 
本题要在所给的n个数中选择2个(可以相同)x、y,使x+y=k,求这样的组合个数(x0 != x1 or y0 != y1就算不同的)。对于本题,我们的想法是任意选一个x,看存不存在这样的y,此时可以建立与n个数对应的hash表,但可能超内存。所以我们应该换种思路。可以尝试二分查找y,要二分就必须先排序,排完序之后还应该去掉相同元素优化方便解题。
#include<iostream>#include<cstdio>#include<algorithm>using namespace std;const int MAXN=100000+100;int n,k;int num[MAXN];int main(){int i,cas;cin>>cas;while(cas--){scanf("%d%d",&n,&k);for(i=0;i<n;i++){scanf("%d",&num[i]);}sort(num,num+n);n=unique(num,num+n)-num;int count=0;for(i=0;i<n;i++){bool flag=false;int Find=k-num[i];int mid,low=i,high=n-1;while(low<=high){mid=(low+high)/2;if(num[mid]==Find){flag=true;break;}else if(num[mid]>Find)high=mid-1;elselow=mid+1;}//printf("num[i]=%d  num[mid]=%d\n",num[i],num[mid]);if(flag){count++;if(num[i]!=num[mid])count++;}}printf("%d\n",count);}return 0;}

原创粉丝点击