51nod 1267 4个数和为0

本文介绍了一种解决特定四数求和问题的方法。通过将原始问题转换为寻找两个数之和等于特定值的问题,并利用排序和双指针技巧进行高效求解。特别注意的是,解决方案中还需确保选取的数字来自不同的位置。

【题解】

  先把数字两两组合,问题转化为求a+b=0. 这个问题显然可以排序后two pointer做。需要注意选出来的两个数必须由4个不同位置的数组成,不能重复。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #define LL long long
 5 #define rg register
 6 #define N 1000010
 7 using namespace std;
 8 int n,tot,a[N],b[N],pos[N][2];
 9 inline int read(){
10     int k=0,f=1; char c=getchar();
11     while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar();
12     while('0'<=c&&c<='9')k=k*10+c-'0',c=getchar();
13     return k*f;
14 }
15 int main(){
16     n=read();
17     for(rg int i=1;i<=n;i++) b[i]=read();
18     for(rg int i=1;i<n;i++)
19         for(rg int j=i+1;j<=n;j++)
20         a[++tot]=b[i]+b[j],pos[tot][0]=i,pos[tot][1]=j;
21     sort(a+1,a+1+tot);
22     int l=1,r=tot;
23     while(l<r){
24         while(a[l]+a[r]>0) r--;
25         if(a[l]+a[r]==0){
26             for(rg int i=r;i>=l;i--)if(a[l]+a[r]==0){
27                 if(pos[l][0]==pos[r][0]||pos[l][1]==pos[r][0]||pos[l][0]==pos[r][1]||pos[l][0]==pos[r][1]) continue;
28                 puts("YES");
29                 return 0;
30             }
31             else break;
32         }
33         l++;
34     }
35     puts("NO");
36     return 0;
37 }
View Code

 

转载于:https://www.cnblogs.com/DriverLao/p/9571946.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值