POJ 2785 4 Values whose Sum is 0

4 Values whose Sum is 0
Time Limit: 15000MS   Memory Limit: 228000K
Total Submissions: 17088   Accepted: 4998
Case Time Limit: 5000MS

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

题目也是要用到二分来做,将A+B C+D分别存在两个数组里面,尝试了用vector 来做然后用find函数来搜索,结果tle,所以有些题目还是老老实实敲,不要搞些骚操作,目前了解的只有set集合类的find函数是二分查找,其它集合类都是用的头文件里面的find函数,比较耗时不推荐使用,但是还有一个小坑就在于,可能会有重复的值出现,所以要加上这些重复的可能;

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std ;
int a[5000],b[5000],c[5000],d[5000];
int num1[25000005],num2[25000005];
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        int t=n;
        int i=0;
        for(int i=0; i::iterator s1=num1.begin(),s2;

        int ans=0;

        for(; s1!=num1.end(); s1++)
        {

             s2=find(num2.begin(),num2.end(),-*s1);
             while(s2!=num2.end()){
                 ans++;
             s2=find(s2+1,num2.end(),-*s1);
                 //cout<<*s1<<*s2<=0; j--)
                        if(num1[i]+num2[j]!=0)
                            break;
                        else
                            ans++;
                    break;

                }
                else if(num2[m]>-num1[i])
                    r=m-1;
                else
                    l=m+1;
            }
        }



        printf("%d\n",ans);
    }
    return 0 ;
}


你可能感兴趣的:(二分)