Wannafly挑战赛4 A.解方程 (二分)

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld
题目描述
给出n个整数和x,请问这n个整数中是否存在三个数a,b,c使得ax2+bx+c=0,数字可以重复使用。
输入描述:
第一行两个整数n,x
第二行n个整数a[i]表示可以用的数
1 <= n <= 1000, -1000 <= a[i], x <= 1000
输出描述:
YES表示可以
NO表示不可以
示例1
输入

2 1
1 -2
输出

YES

题意:

题解:

暴力模拟的话N3的时间复杂度肯定不行,可以模拟出ax2+bx的所有结果,然后二分查找-c,时间复杂度为N2 logN。

#include<iostream>
#include<algorithm>
using namespace std;
int a[2005];
int n;
bool check(int x)
{
    int lb=0,ub=n-1;
    while(lb<ub)
    {
        int mid=(lb+ub)>>1;
        if(x==a[mid])
            return true;
        else if(x>a[mid])
            lb=mid+1;
        else
            ub=mid-1;
    }
    return false;
}
int main()
{
    int x;
    cin>>n>>x;
    for(int i=0;i<n;i++)
        cin>>a[i];
    sort(a,a+n);
    bool flag=false;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            int t=a[i]*x*x+a[j]*x;
            if(-t>a[n-1]||-t<a[0])
                continue;
            if(check(-t))
            {
                cout<<"YES"<<endl;
                flag=true;
                break;
            }
        }
        if(flag)
            break;
    }
    if(!flag)
        cout<<"NO"<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/orion7/p/7894466.html