Dating with girls(1)
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4243 Accepted Submission(s): 1326
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!
2 5 4 1 2 3 4 5 8 8 1 4 5 7 8 9 2 6
3 5
此题主要考察了二分查找的运用,经过此题我发现自己还很嫩啊,要好好学扎实了才行!
注意相同的数字只算一个,要排除相同的
代码如下
#include<cstdio>
#include<algorithm>
using namespace std;
int Binary_Search(int a[],int n,int k)
{
int low,high,mid,counter=0;
for(int i=0;i<n;i++)
{
if(a[i]==a[i+1])
continue;
low=0,high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]+a[i] > k)
high = mid -1;
else if(a[mid]+a[i] < k)
low = mid +1;
else
{
counter++;
break;
}
}
}
return counter;
}
int main()
{
int i,n,t,k,counter;
int a[100005];
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
sort(a,a+n);//用sort函数进行升序
counter=Binary_Search(a,n,k);
printf("%d\n",counter);
}
return 0;
}