Ok, here is my algorithm O (n ^ 2lg (n ^ 2)) -
Suppose that there are four arrays A [], B [], C [], D []. we want to find the number of paths A [i] + B [j] + C [k] + D [l] = 0, where 0 <= i, j, k, l <n.
So, we summarize all the possible locations of A [] and B [] and put them in another array E [], which contain n * n number of elements.
int k=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) { E[k++]=A[i]+B[j]; } }
Code complexity above O (n ^ 2).
Do the same for C [] and D [].
int l=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) { AUX[l++]=C[i]+D[j]; } }
Code complexity above O (n ^ 2).
Now sort AUX [] so that you can easily find the number of occurrences of the unique element in AUX [].
The complexity sorting AUX [] is O (n ^ 2 log (n ^ 2)).
now declares a structure -
struct myHash { int value; int valueOccuredNumberOfTimes; }F[];
Now in the F [] structure, place the unique AUX [] element and the amount of time in which they appeared.
Difficulty is O (n ^ 2)
possibleQuardtupple=0;
Now for each element E [] do the following
for(i=0;i<k;i++) { x=E[i]; find -x in structure F[] using binary search. if(found in j'th position) { possibleQuardtupple+=number of occurrences of -x in F[j]; } }
For the loop, I perform the total number of iterations n ^ 2 and in each iterate for the binary search lg (n ^ 2). So overall the complexity is O (n ^ 2 log (n ^ 2)).
Number of paths reached 0: = possibly Quardtupple.
Now you can use stl map / binary search. But the stl map is slow, so it is better to use binary search.
Hope my explanation is clear enough to understand.