POJ_2785_4 values whose sum is 0_折半枚举

本文介绍了一个经典的算法问题——从四个长度相同的数组中各选一个数字使其和为零,通过使用折半枚举技术和二分搜索算法来高效解决该问题。

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

最近AC率好低啊。。。


题意:

给四个长度为n的数组,问有多少种选择方法,使得从四个数组中各选出一个数字,求和等于0.(数值相同的不同元素也算不同选择方法)



Input

The first line of the input file contains the size of the lists n (this value can be as large as 4000). We then have n lines containing four integer values (with absolute value as large as 228 ) that belong respectively to A, B, C and D .

Output

For each input file, your program has to write the number quadruplets whose sum is zero.


用折半枚举,预处理出后两个数组的和,枚举前两个数组的和,二分搜索。

注意手写二分搜索可能存在找不到符合条件的元素的情况,此时l会等于n-1,应当判断a[l]是否符合情况,不符合就加一,被坑了一次。


代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
#define mxn 4010
int n,cnt;
int a[4][mxn];
int sum[2][mxn*mxn];
int upperbound(int tgt){
	int l=0,r=cnt,m;
	while(l+1<r){
		m=(l+r)/2;
		if(sum[1][m]>tgt)	r=m;
		else	l=m;
	}
	return sum[1][l]>tgt ? l : l+1;
}
int lowerbound(int tgt){
	int l=0,r=cnt,m;
	while(l+1<r){
		m=(l+r)/2;
		if(sum[1][m]>=tgt)	r=m;
		else	l=m;
	}
	return sum[1][l]>=tgt ? l : l+1;
}
int main(){
	scanf("%d",&n);
	for(int i=0;i<n;++i)
		for(int j=0;j<4;++j)
			scanf("%d",&a[j][i]);
	cnt=0;
	for(int i=0;i<n;++i)
		for(int j=0;j<n;++j){
			sum[0][cnt]=a[0][i]+a[1][j];
			sum[1][cnt++]=a[2][i]+a[3][j];
		}
	sort(sum[0],sum[0]+cnt);
	sort(sum[1],sum[1]+cnt);
	int ans=0;
	for(int i=0;i<cnt;++i)
		ans+=upperbound(-sum[0][i])-lowerbound(-sum[0][i]);
	printf("%d\n",ans);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值