4个数和为0 51Nod - 1267

4个数和为0

51Nod - 1267

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

Input 第1行,1个数N,N为数组的长度(4 <= N <= 1000)
第2 - N + 1行:Ai(-10^9 <= Ai<= 10^9) Output 如果可以选出4个数,使得他们的和为0,则输出"Yes",否则输出"No"。 Sample Input
5
-1
1
-5
2
4
Sample Output
Yes

code:


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1011;
int n;
struct node{
    ll s;
    int i,j;
}sum[maxn*maxn];
ll a[maxn];
int cnt = 0;
int id = -1;
bool cmp(node a,node b){
    return a.s < b.s;
}
int F(ll x){
    int l = 0,r = cnt-1;
    while(l <= r){
        int mid = (l + r) >> 1;
        if(sum[mid].s == x){
            id = mid;
            return 1;
        }
        else if(sum[mid].s < x)
            l = mid + 1;
        else
            r = mid - 1;
    }
    return 0;
}
int main(){
    scanf("%d",&n);
    for(int i = 0; i < n; i++){
        scanf("%lld",&a[i]);
    }
    for(int i = 0; i < n; i++){
        for(int j = i+1; j < n; j++){
            sum[cnt].s = a[i] + a[j];
            sum[cnt].i = i;
            sum[cnt++].j = j;
        }
    }
    sort(sum,sum+cnt,cmp);
    int flag = 0;
    for(int i = 0; i < cnt; i++){
        id = -1;
        int k = F(-sum[i].s);
        if(id == -1) continue;//如果没找到跳过
        if(sum[i].i == sum[id].i || sum[i].i == sum[id].j || sum[i].j == sum[id].i || sum[i].j == sum[id].j)//确保没有重复的数字
            continue;
        if(k){
            flag = 1;
            break;
        }
    }

    if(!flag) printf("No\n");
    else printf("Yes\n");
    return 0;
}



展开阅读全文

没有更多推荐了,返回首页