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 228 ) 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 -46 26 -38 -10 62 -32 -54 -6 45
Sample Output
5
解题思路:
由于用暴力求解需要四个for循环,这样时间复杂度过高,这里可以进行优化4列分为两组,两列两列为一组,然后分别计算他们的组合,放到p,q数组中,然后通过二分在q数组中找p数组的数的相反数,由此来解决问题。
AC代码
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 4010;
int arr[N][6];
int p[N * N];
int q[N * N];
int n;
//将四列分成两列处理
void func(int* a, int x, int y)
{
int cnt = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
a[++cnt] = arr[i][x] + arr[j][y];
}
}
}
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%d%d%d%d", &arr[i][1], &arr[i][2], &arr[i][3], &arr[i][4]);
}
func(p, 1, 2);
func(q, 3, 4);
sort(q + 1, q + 1 + n * n);
long long cnt = 0;
for (int i = 1; i <= n * n; i++)
{
cnt += upper_bound(q + 1, q + 1 + n * n, -p[i]) - lower_bound(q + 1, q + 1 + n * n, -p[i]);
}
cout << cnt << endl;
return 0;
}