1267 4个数和为0(不放回的取 4 个)

1267 4个数和为0

  1. 1 秒
  2.  
  3. 131,072 KB
  4.  
  5. 20 分
  6.  
  7. 3 级题

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

 收起

输入

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

输出

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

输入样例

5
-1
1
-5
2
4

输出样例

Yes

题解:见代码

#include<set>
#include<map>
#include<list>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<bitset>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define eps (1e-8)
#define MAX 0x3f3f3f3f
#define u_max 1844674407370955161
#define l_max 9223372036854775807
#define i_max 2147483647
#define re register
#define pushup() tree[rt]=tree[rt<<1]+tree[rt<<1|1]
#define nth(k,n) nth_element(a,a+k,a+n);  // 将 第K大的放在k位
#define ko() for(int i=2;i<=n;i++) s=(s+k)%i // 约瑟夫
using namespace std;

inline int read(){
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' & c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}

typedef long long ll;
const double pi = atan(1.)*4.;
const int M=1e3+5;
const int N=1e6+5;
ll a[1005];
int n;
bool fun(){
    for(int i=0;i<n-1;i++){
        for(int j=i+1;j<n;j++){
            ll ans=-a[i]-a[j];
            int l=j+1,r=n-1;
            while(l<r){            // 进行尺取
                ll sum=a[l]+a[r];
                if(sum==ans)
                   return true;
                else if(sum<ans)
                   l++;
                else
                   r--;
            }
        }
    }
    return false;
}
int main(){
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%lld",&a[i]);
    sort(a,a+n);
    if(fun())  printf("Yes\n");
    else printf("No\n");
    return 0;

}

猜你喜欢

转载自blog.csdn.net/black_horse2018/article/details/83787717