# 二分查找

165人阅读 评论(0)

There are m positive integers in set S.can we find two elements in set s and the sum of them equal to X?

Input

The first line of the input file contains a single integer n(the number of test cases)(2=<n<=3000),Each test case consist of two lines,the first line containing an integer m(the number of elements in set S)(2<=m<=2011), followed by an integer x(0<=x<=20000) , the next line contains m positive integers.

Output

For each test case you should output "YES" (if the sum of two elements in set S equal to x),or "NO"(if not).

Sample Input

2
3 5
1 2 3
4 10
1 2 3 4

Sample Output

YES

NO

#include<iostream>
using namespace std;
#define MAX 2015

int binarySearch(int a[],int low,int high,int cnt)
{
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==cnt)
return 1;
else
if(a[mid]<cnt)
low=mid+1;
else
high=mid-1;
}
return 0;
}

int main()
{
int n,m,x,i;
int a[MAX];
cin>>n;
while(n--)
{
memset(a,0,MAX);
cin>>m>>x;
for(i=0;i<m;i++)
cin>>a[i];
int k=0;
for(i=0;i<m;i++)
if(a[i]<=x/2&&a[i+1]>x/2)
k=i;
int flag=0;
if(k==0)
cout<<"NO"<<endl;
else
{
for(i=k+1;i<m;i++)
if(binarySearch(a,0,k,x-a[i]))
{
flag=1;
break;
}
if(flag)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
return 0;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：20610次
• 积分：305
• 等级：
• 排名：千里之外
• 原创：15篇
• 转载：3篇
• 译文：0篇
• 评论：0条