Dating with girls(1)Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4837 Accepted Submission(s): 1534
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
Sample Output
|
题意:
求有多少对x,y(x,y属于输入的n个数)满足x+y=k。
题解:
原式可以得到y=k-x,遍历n个数,用二分查找查找n个数里面是否含有k-a[i],注意去重。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,k,a[100005];
int f(int x)
{
int left=0,right=n-1,mid;
while(left<=right)
{
mid=(left+right)/2;
if(a[mid]==x)
return 1;
else if(a[mid]<x)
left=mid+1;
else
right=mid-1;
}
return 0;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
int res=0;
for(int i=0;i<n;i++)
{
if(i && a[i]==a[i-1])
continue;
if(f(k-a[i]))
res++;
}
printf("%d\n",res);
}
return 0;
}