二分_E

来源:互联网 发布:谷阿莫华尔街之狼 知乎 编辑:程序博客网 时间:2024/04/28 01:26

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

与前面的题类似,先前两个求和,后两个求和,然后二分即可

#include<iostream>#include"algorithm"#include<cstring>using namespace std;#define num 4010static int arr1[num],arr2[num],arr3[num],arr4[num],arr_1[num*num],arr_2[num*num];int binary(int,int);int main(){  int T;  while(cin>>T){    for(int i=0;i<T;i++){      cin>>arr1[i]>>arr2[i]>>arr3[i]>>arr4[i];    }    int N=0,M=0;    for(int i=0;i<T;i++){      for(int j=0;j<T;j++){        arr_1[N++]=arr1[i]+arr2[j];        arr_2[M++]=arr3[i]+arr4[j];      }    }    sort(arr_1,arr_1 + N);int Count=0;    for(int i=0;i<M;i++){      Count+=(binary(-arr_2[i],T*T-1));    }    cout<<Count<<endl;    memset(arr_1,-1,sizeof(arr_1));    memset(arr_2,-1,sizeof(arr_2));  }  return 0;}/**гажиИДжЕ**/int binary(int key,int high){  int low=0;  int mid=0;  int ans=0;  int len=high;  while(low<=high){    mid=((high-low)>>1)+low;    if(arr_1[mid]==key) {      ans++;      for(int k=mid+1;k<high;k++){        if(arr_1[k]==key) ans++;        else break;      }      for(int k=mid-1;k>=0;k--){        if(arr_1[k]==key) ans++;        else break;      }      break;    }    else if(arr_1[mid]>key) high=mid-1;    else low=mid+1;  }  return ans;}


0 0
原创粉丝点击