二分贪心练习题--D(四个数和为0的组合数)

来源:互联网 发布:常见的网络交流平台 编辑:程序博客网 时间:2024/05/16 01:01

题意描述:

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 -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).
题意理解:

由题意可知,输入的数字每一列为一个数组,每个数组中取一个元素,求取出的四个数中能求得和为0的组合数。该题意可从Hint中看出来。

解题思路:

1、首先要将数据输入,即建立四个数组。然后存放每一组数。

2、因为一个一个找需要四重循环,一定是会超时的。所以首先将第一个数组(a)和第二个数组(b)的和计算出来,然后存放到sum_ab数组里,将该数组从小到大排序。

3、然后用一个双重循环,在循环内求一个sum_cd,然后在sum_ab中找,这个时候为了避免超时就需要用二分法进行查找,查找和sum_cd的和为0的值,然后以该值为中心,求前后是否有相同的数,然后sun++,即组合数自增。

4、该题主要就只用二分法查找,学会用二分法。

源代码:

#include <iostream>#include <stdio.h>#include <vector>#include <cstring>#include <algorithm>using namespace std;int main(){    int n,i;    scanf("%d",&n);    int a[4005],b[4005],c[4005],d[4005],sum=0;    for (i=0;i<n;i++)        cin>>a[i]>>b[i]>>c[i]>>d[i];    int j,t=0;    vector <int> sum_ab;    for (i=0;i<n;i++)        for (j=0;j<n;j++)        {            sum_ab.push_back( a[i] + b[j]);            t++;        }    stable_sort(sum_ab.begin(),sum_ab.end());    int lp,rp,mid;    for (i=0;i<n;i++)    {        for (j=0;j<n;j++)        {            int sum_cd=c[i]+d[j];            lp=0;            rp=t-1;            while (lp<rp)            {                mid=(lp+rp)/2;                if (sum_ab[mid]+sum_cd==0)                {                    sum++;                    for (int q=mid-1;q>=0;q--)                    {                        if (sum_ab[q]+sum_cd==0)                            sum++;                        else                            break;                    }                    for (int q=mid+1;q<t;q++)                    {                        if (sum_ab[q]+sum_cd==0)                            sum++;                        else                            break;                    }                    lp=mid+1;                    rp=mid;                }                else if (sum_ab[mid]+sum_cd>0)                    rp=mid;                else if (sum_ab[mid]+sum_cd<0)                    lp=mid+1;            }        }    }        printf("%d\n",sum);    return 0;}

0 0