POJ2785 4 Values whose Sum is 0(暴力二分查找)

81 阅读2分钟

\

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

    \

    思路:

    题目是要求四个数相加之和为零, 我们可以两 两相加, 这样的话就变成是求两个数之和为0了,再进一步想就是在另一个数组中找相反数,利用low_bound

    ()和up_bound可以快速的二分查找。

    \

    #include<iostream>
    #include<cstdio>
    #include<algorithm>
    
    using namespace std;
    const int mx = 4050;
    int a[mx], b[mx], c[mx], d[mx];
    int n, sum1[mx * mx], sum2[ mx * mx];
     void slove(){
     	 int cnt =0, nn = n * n;
     	 sort(sum1, sum1 + nn);
     	 
    	 for(int i = 0; i < nn; i++){
    	 	cnt += upper_bound(sum1, sum1+ nn, -sum2[i]) - lower_bound(sum1, sum1+ nn, -sum2[i]); //记得负号 
    	 }
    	 cout<<cnt<<endl;
     }
    int main(){
    	while(scanf("%d", &n) != EOF){
    		
    		for(int i = 0; i < n; i++)
    			scanf("%d%d%d%d", &a[i], &b[i], &c[i], &d[i]);
    	
    		int c1 = 0, c2 = 0; 
    		for(int i =0; i < n; i++)
    			for(int j =0; j < n; j++){
    			sum1[c1++] = a[i] + b[j];
    			sum2[c2++] = c[i] + d[j];
    		}	
    		
    		slove();
    	}
    
    	return 0;
    }
    


    \

    \

    \

本文已参与「新人创作礼」活动,一起开启掘金创作之路