CSU-ACM2017暑假集训2-二分搜索 poj-2785-4 Values whose Sum is 0

来源:互联网 发布:2016高速公路数据分析 编辑:程序博客网 时间:2024/06/01 08:01

题目:

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 -4626 -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).
           

          题意:给你4个数组A,B,C,D ,问每个数组取一个数求和a+b+c+d=0的方案书有多少种。

          思路:一开始是合并AB数组,CD数组,然后对AB数组排序,枚举CD数组,再在AB数组中二分查找,如果找到了,还要在找到的位置前后寻           找是否有相同元素存在,这些元素都会是的情况数增加。这么写超时了,后来改成先用map计算出重复元素,还是超时。最后使用STL中给的           二分方法并且二分查找最后一个 与第一个,他们的差值就是满足情况的相同要元素个数。

          代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <map>#define long long LL#define N 4004using namespace std;int n;int sum;int a[N],b[N],c[N],d[N];int a_b[N*N],c_d[N*N];int num_ab,num_cd;void init(){    int k,t;    k=t=0;    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++)        {            a_b[k++]=a[i]+b[j];        }    }    for(int i=0;i<n;i++)    {        for(int j=0;j<n;j++)        {            c_d[t++]=c[i]+d[j];        }    }    num_ab=k;    num_cd=t;    sort(a_b,a_b+k);}int main(){    while(scanf("%d",&n)!=EOF)    {        init();        sum=0;        for(int i=0;i<num_cd;i++)        {            int t=0-c_d[i];            sum+=upper_bound(a_b,a_b+num_ab,t)-lower_bound(a_b,a_b+num_ab,t);        }        printf("%d\n",sum);    }    return 0;}


原创粉丝点击