HDU 5522 Numbers(模拟,问数组中是否存在任意2个数字的和在数组中)
原创
©著作权归作者所有:来自51CTO博客作者mb62ea10deefd92的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目地址:点击打开链接
思路:我用了2个for循环+2分搜索过了,怕超时,队友用3个for循环也过了
AC代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
using namespace std;
int a[1010];
bool flag;
int zai[100010];
int n;
bool bsearch(int begin1,int goal)
{
int left =begin1,right = n - 1,mid;
while(left <= right)
{
mid = (left + right) / 2;
if(a[mid] == goal)
return true;
else if(a[mid] < goal)
left = mid + 1;//注意分号敲错
else
right = mid - 1;
}
return false;
}
int main()
{
int i,j;
while(scanf("%d",&n) != EOF)
{
memset(zai,0,sizeof(zai));
flag = false;
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
sort(a,a+n);
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
int sum = a[i] + a[j];
if(bsearch(j+1,sum))
{
flag = true;
break;
}
}
if(flag)
break;
}
if(flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}