Given each of the four series with n integers, a,b,c,d. To take 1 numbers from each column, make four numbers. Find out the number of such combinations, when there are multiple identical numbers in a sequence, treat them as different numbers.
Input: n=6
A={-45,-41,-36,-36, 26,-32};
B={22,-27, 53, 30,-38,-54};
C={42, 56,-37, 75,-10,-6};
D={-16, 30, 77,-46, 62, 45};
Output: 5 ( -45-27+42+30=0,26+30-10-46=0,-32+22+56-46=0,-32+30-75+77=0,-32-54+56+30=0)
Analysis: From these four series of choice, there are always n of the 4 times in the case, so all the judgment can not be done again. But it can be solved by dividing them into AB and CDs. If you choose from two series, only 2 of the n is combined. So you can enumerate. After removing a A, b from a A, to make the sum of 0 need to remove a+b=-(c+d) from the C,d, the first and second arrays of A and B in an array AB, and then add C and d the opposite number-(c+d) in the AB array to find, with a binary search.
#include <iostream> #include <stdio.h> #include <string.h> #include <algorithm>using namespace Std;int Main () { int a[4040];int b[4040];int ab[8080]; int C[4040];int d[4040]; int n; while (Cin>>n) {for (int i=0;i<n;i++) cin>>a[i]; for (int i=0;i<n;i++) cin>>b[i]; for (int i=0;i<n;i++) cin>>c[i]; for (int i=0;i<n;i++) cin>>d[i]; int count1=0; for (int. i=0;i<n;i++) for (int j=0;j<n;j++) ab[count1++]=a[i]+b[j]; Sort (ab,ab+n*n); int res=0; for (int i=0;i<n;i++) for (int j=0;j<n;j++) { int cd=-(c[i]+d[j]); Res+=upper_bound (AB,AB+N*N,CD)-lower_bound (AB,AB+N*N,CD); } cout<<res<<endl; }}
Binary Enumeration (bidirectional search)