解题报告 之 UVA1152 4 Values Whose Sum is Zero
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 ) AxBxCxD are such that a + b + c + d = 0 . In the following, we assume that all lists have the same size n .
Input
The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
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 test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.
For each input file, your program has to write the number quadruplets whose sum is zero.
Sample Input
1 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
Sample Explanation: Indeed, the sum of the five following quadruplets is zero: (-45, -27, 42, 30), (26, 30, -10, -46), (-32, 22, 56, -46),(-32, 30, -75, 77), (-32, -54, 56, 30).
题目大意:给出4个数据集A,B,C,D,从其中各取一个数字,问取出的数字相加等于0有多少种取法?
好吧,不得不承认一开始用Hash表来弄时间跪了。后来看了一下分析是中途相遇法。最朴素的想法是枚举A,B,C,D。复杂度O(n^4),只能呵呵哒。然后再想想发现可以枚举A,B,C,再看与D中有没有其相反数。然而复杂度仍然是O(n^3*logn)——枚举+查找。所以顺着这样想,就是中间相遇法,即枚举A+B和C+D,再在C+D中去查找A+B的相反数。那么复杂度就是O(n^2*logn)。
先按照紫书说的用hash结果时间挂掉了,估计是查找没有优化还是O(n^3)。于是乎看了一下题解。发现了一个高端的方法,先将A+B排序,在使用STL,upper_bound(a,a+n,key)和lower_bound(a,a+n,key)。upper_bound是返回a~a+n之间第一个大于key的迭代器而lower_bound是返回第一个大于等于的迭代器,则两个结果相减就是key的个数,那么我们这道题就是用upper_bound(aab,aab+cnt,-C[i]-D[j])- lower_bound(aab,aab+cnt,-C[i]-D[j])就可以了。
下面上代码:
#include <iostream>
#include <cmath>
#include <algorithm>
#define MAXN 4010
using namespace std;
long long a[MAXN], b[MAXN], c[MAXN], d[MAXN];
long long aab[MAXN*MAXN];
int main()
{
int kase, n;
cin >> kase;
while (kase--)
{
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i] >> b[i] >> c[i] >> d[i];
}
long long cnt = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
aab[cnt++] = a[i] + b[j];
}
}
sort(aab, aab + cnt);
int ans = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
ans += upper_bound(aab, aab + cnt, -c[i] - d[j]) - lower_bound(aab, aab + cnt, -c[i] - d[j]);
}
}
cout << ans << endl;
if (kase) cout << endl;
}
return 0;
}
另外有几道中途相遇法的题,先列在这以后做吧,毕竟最近再赶任务。
hdu 4963 Dividing a String
uva 1326 Jurassic Remains
POJ1903 - Jurassic Remains