基准时间限制:1 秒 空间限制:131072 KB 分值: 20
难度:3级算法题
给出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"。
Input示例
5 -1 1 -5 2 4
Output示例
Yes
思路:a+b+c+d=0 -> a+b=-(c+d)
预处理两两数的和并记录这两个数的下标,排序后不断从头和尾看是否匹配
需要注意不能重复选择同一个数,所以检查匹配的时候要检查下标,
#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <cstring>
#include <queue>
#include <algorithm>
#define ll long long
#define max_ 100100
using namespace std;
struct node
{
ll w;
int i,j;
};
struct node pre[1001000];
int n;
ll num[1010];
bool cmp(struct node a,struct node b)
{
return a.w<b.w;
}
bool check(int i,int j)
{
if(pre[i].w==-pre[j].w)
{
if(pre[i].i!=pre[j].i&&pre[i].i!=pre[j].j&&pre[i].j!=pre[j].i&&pre[i].j!=pre[j].j)
return true;
}
return false;
}
int main(int argc, char const *argv[]) {
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%lld",&num[i]);
int cnt=0;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
cnt++;
pre[cnt].i=i;
pre[cnt].j=j;
pre[cnt].w=num[i]+num[j];
}
}
sort(pre+1,pre+1+cnt,cmp);
int f=0;
int i=1,j=cnt;
while(i<j)
{
if(check(i,j))
{
f=1;
break;
}
if(-pre[i].w<pre[j].w)
j--;
else
i++;
}
if(f)
printf("Yes\n");
else
printf("No\n");
return 0;
}