如题,有四个数组,分别从四个数组中挑选一个数字使得四个数字之和为0,问有多少种这样的组合。
四个数组总共有n^4种情况,但是如果使用用折半枚举的方法,只需枚举出数组A与数组B中n^2中情况,将这些情况排序后就可以用二分搜索将算法的复杂度降低到n^2logn.
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 4000 + 10;
int A[maxn], B[maxn], C[maxn], D[maxn];
int AB[maxn*maxn];
int main(int argc, char const *argv[]) {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d%d%d%d", &A[i], &B[i], &C[i], &D[i]);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
AB[i*n+j] = A[i] + B[j];
}
}
sort(AB, AB + n * n);
long long 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);
}
}
printf("%lld\n", res);
return 0;
}