您的位置:首页 > 产品设计 > UI/UE

POJ_2785_4 values whose sum is 0_折半枚举

2014-11-06 19:17 441 查看
最近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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: