51Nod 1267 4个数和为0 ( 二分

探讨了如何高效地从数组中找出四个整数,使其和为零的问题。通过使用预处理和二分查找的方法避免了暴力求解的高时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1267 4个数和为0

Description

给出N个整数,你来判断一下是否能够选出4个数,他们的和为0,可以则输出”Yes”,否则输出”No”。

Input

第1行,1个数N,N为数组的长度(4 <= N <= 1000)
第2 - N + 1行:A[i](-10^9 <= A[i] <= 10^9)

Output

如果可以选出4个数,使得他们的和为0,则输出”Yes”,否则输出”No”。

Sample Input

5
-1
1
-5
2
4

Sample Output

Yes

题意

从数组中找来4个数字进行判断相加是否为0

题解:

暴力肯定是不行的n^3就GG了
这里就发现一个特别好的思路,将一个数组内的数字两两相加(不重复)存起来 然后在排序1e6个数 用二分查找 记住标记下相加之前时的位置 就可以了

AC代码

#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define ll long long
const int mod = 1e9+7;
const int N = 1010;
int arr[N];
struct node {
    int x, y;
    int sum;
}p[N*N];
bool cmp(node x, node y)
{
    return x.sum < y.sum;
}
int main()
{
    int n;
    bool flag = false;
    scanf("%d",&n);
    for(int i = 0; i < n; i++)
        scanf("%d",&arr[i]);
    int k = 0;
    sort(arr,arr+n); 
    for(int i = 0;i < n; i++) {    //使数组内的任意两个数相加且不重复 
        for(int j = i+1;j < n; j++) {
            p[k].x = i;                  //标记每两个相加过的数字 
            p[k].y = j;
            p[k++].sum = arr[i] + arr[j];
        }
    }
    sort(p,p+k,cmp);                
    int low = 0, top = k-1;                         
    while(low < top) {
        if(p[low].sum+p[top].sum==0&&p[low].x!=p[top].x && p[low].x!=p[top].y && p[low].y!=p[top].x && p[low].y!=p[top].y) {  //判断数字自身是否重复想加 
            flag = true; break; 
        }
        else if(p[low].sum+p[top].sum< 0) low++;
        else top--; 
    }
    if(flag) puts("Yes");
    else puts("No"); 
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值