HDU 5522 Numbers(枚举 + 二分查找)

Problem Description
There are n numbers A1,A2....An ,your task is to check whether there exists there different positive integers i, j, k ( 1i,j,kn ) such that AiAj=Ak
 

Input
There are multiple test cases, no more than 1000 cases.
First line of each case contains a single integer n. (3n100) .
Next line contains n integers A1,A2....An . (0Ai1000)
 

Output
For each case output "YES" in a single line if you find such i, j, k, otherwise output "NO".
 

Sample Input
  
  
3 3 1 2 3 1 0 2 4 1 1 0 2
 

Sample Output
  
  
YES NO YES
 

题目大意:给出 n 个数,问能不能找到三个满足Ai - Aj = Ak。

乍一看没思路,一看数据范围100就呵呵了。给这些数从小到大排个序,Ai - Aj = Ak 也可以看成是找 Ai + Aj = Ak。Ak 一定是由比它小的 Ai 和 Aj 加起来得到的,从前往后枚举即可。枚举 Ai 和 Aj 再从数列里二分找 Ak,复杂度最坏 O(n^2logn)。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100 + 5;
int a[maxn];
int main()
{
    int n;
    while(scanf("%d",&n) != EOF)
    {
        for(int i = 0;i < n; ++i) scanf("%d",&a[i]);
        sort(a,a + n);
        bool ok = false;
        for(int i = 0;i < n; ++i)
        {
            for(int j = i + 1;j < n; ++j)
            {
                int p = lower_bound(a + j + 1,a + n,a[i] + a[j]) - a;
                if(p < n && a[p] == a[i] + a[j])
                {
                    ok = true;
                    break;
                }
            }
            if(ok) break;
        }
        printf("%s\n",ok ? "YES" : "NO");
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值