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

POJ 2785 4 Values whose Sum is 0

2016-07-08 22:33 465 查看
链接:http://poj.org/problem?id=2785

题意:一组4个数,给出若干组,输出有多少对组合满足四个数之和为0

将四列数并成两列,对两列二分查找

#include <cstdio>
#include <algorithm>
using namespace std;
int t[4010][4];
int first2[4000*4000+4],last2[4000*4000+4];
int Binsearch(int total,int key) {
int l=0,r=total-1;
bool flag=0;
while(l<=r) {
int mid=(l+r)>>1;
if(first2[mid]==key) {
flag=1;
break;
} else if(first2[mid]>key) r=mid-1;
else l=mid+1;
}
if(flag) {
int sum;
for(sum=0; l<total; l++) {
if(first2[l]==key) sum++;
if(sum && first2[l]!=key) break;
}
return sum;
}
return 0;
}
int main() {
int n;
while(~scanf("%d",&n)) {
int k=0;
for(int i=0; i<n; i++) for(int j=0; j<4; j++) scanf("%d",&t[i][j]);
for(int i=0; i<n; i++)
for(int j=0; j<n; j++) {
first2[k]=t[i][0]+t[j][1];
last2[k++]=t[i][2]+t[j][3];
}
sort(first2,first2+k);
sort(last2,last2+k);
int ans=0;
for(int i=0; i<k; i++) ans+=Binsearch(k,-last2[i]);
printf("%d\n",ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二分查找 poj