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

poj 2785 4 Values whose Sum is 0

2016-09-03 10:43 302 查看
4 Values whose Sum is 0Time Limit:15000MS    Memory Limit:228000KB    64bit IO Format:%lld
& %llu
SubmitStatusPracticePOJ
2785
Description

The SUM problem can be formulated as follows: given four lists A, B, C, D of integer values, compute how many quadruplet (a, b, c, d ) ∈ A x B x C x D are such that a + b + c + d = 0 . In the following, we assume that all lists
have the same size n .

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 2
28 ) 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.

Sample Input

6
-45 22 42 -16
-41 -27 56 30
-36 53 -37 77
-36 30 -75 -46
26 -38 -10 62
-32 -54 -6 45


Sample Output

5


Hint

Sample Explanation: Indeed, the sum of the five following quadruplets is zero: (-45, -27, 42, 30), (26, 30, -10, -46), (-32, 22, 56, -46),(-32, 30, -75, 77), (-32, -54, 56, 30).

解题报告:

    二分法的stl:

   upper_bound(a,a+k,value)---返回一个递增序列中第一个大于value的位置;

   lower_bound(a,a+k,value)---返回一个递增序列中第一个大于等于value的位置;

code:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<stack>
#include<math.h>
#include<string>
#include<cstring>

using namespace std;
typedef long long ll;
const int MAX=4005;
int a[MAX],b[MAX],c[MAX],d[MAX],e[MAX*MAX],f[MAX*MAX];
int k=0,t=0;
int n,sum=0;

int main()
{
// freopen("input.txt","r",stdin);
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++){
e[k++]=a[i]+b[j];
f[t++]=c[i]+d[j];
}
sort(e,e+k);
sort(f,f+t);
for(int i=0;i<k;i++){
sum=sum+upper_bound(f,f+t,-1*e[i])-lower_bound(f,f+t,-1*e[i]);
}
printf("%d\n",sum);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息