Test instructions: Give 4 arrays, choose a number from each array, and find out the number of 4 and 0 schemes.
Analysis: Violence time complexity is n^3, certainly not. So consider first the AB, the CD, and the separate to find out. -(A+B) =c+d that satisfies the condition, the summation complexity is n*n. The AB array is-(A+B), the CD array is (C+D).
From the CD array, find the equivalent of the AB array. You can sort the array first, and then use the binary search to find it. The complexity is O (N*N*LOGN).
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include < algorithm> #include <queue> #include <set> #include <map> #include <vector> #include < Cmath> #define LL __int64#define INF 0x3fffffff#define M 4005using namespace Std;int n;int a[m],b[m],c[m],d[m];int Ab[M *m],cd[m*m];int Main () {//freopen ("D:\\test.txt", "R", stdin); while (Cin>>n) {for (int i=0;i<n;i++) {scanf ("%d%d%d%d", &a[i],&b[i],&c[i],&d[i]); } int k1=0; for (int. i=0;i<n;i++) {for (int j=0;j<n;j++) {ab[k1++]=-a[i]-b[j]; }} int k2=0; for (int. i=0;i<n;i++) {for (int j=0;j<n;j++) {cd[k2++]=c[i]+d[j]; }} sort (AB,AB+K1); Sort (CD,CD+K2); ll Ans=0; for (int i=0;i<k1;i++) {ans+=upper_bound (Cd,cd+k2,ab[i])-lower_bound (Cd,cd+k2,ab[i]); }cout<<ans<<endl; } return 0;}
POJ 2785 4 Values whose Sum is 0 (bidirectional search + two points)