4 Values whose Sum is 0
Time Limit: 15000MS |
|
Memory Limit: 228000K |
Total Submissions: 17658 |
|
Accepted: 5187 |
Case Time Limit: 5000MS |
Description
the SUM problem can formulated as Follows:given four lists A, B, C, D of integers values, compute how many QUADRUPL ET (A, B, C, D) ∈a x B x C x D is such that A + B + c + d = 0. In the following, we assume this all lists has 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 had 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 of the input file, your program have 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-4626-38-10 62-32-54-6 45
Sample Output
5
Hint
Sample Explanation:indeed, the sum of the five following quadruplets is zero: (-45,-27, 42, 30), (26, 30,-10,-46), ( -32, -46), ( -32, -32, -75, and -54), ( +/-).
Source
southwestern Europe 2005
Topic Link: http://poj.org/problem?id=2785
The main topic: give four groups of numbers, one column, from each group to take one out to make four add to 0, ask how many scenarios
Topic Analysis: A + B + c + d = 0 ==> A + b =-c-d, we first preprocess the first two groups can be composed of the value of the complexity of the n^2 And then sort after binary search, here the easiest way is to find out upper_bound (num, num + cnt,-c-d)-Num,lower_bound (num, num + cnt ,-c-d)-Num, which represents the first position in the NUM array greater than-c-d, which represents the first position in the NUM array that is greater than or equal to-c-d, and then the number of equal to-c-d by one minus
#include <cstdio> #include <cstring> #include <algorithm> #include <set> #include <iostream > #define LL Long longusing namespace Std;int Const MAX = 4e3 + 5;int A[max], B[max], C[max], d[max];int Num[max * MAX]; int main () {int n; while (scanf ("%d", &n)! = EOF) {ll ans = 0; int cnt = 0; for (int i = 1; I <= n; i++) scanf ("%d%d%d", &a[i], &b[i], &c[i], &d[i]); for (int i = 1, i <= N; i++) for (int j = 1; J <= N; j + +) Num[cnt + +] = A[i] + b[j]; Sort (num, num + cnt); for (int i = 1, i <= N; i++) {for (int j = 1; J <= N; j + +) {int tmp =-C [i]-d[j]; int t1 = lower_bound (num, num + CNT, TMP)-num; int t2 = upper_bound (num, num + CNT, TMP)-num; Ans + = (ll) (T2-T1); }} cout << ans << endl; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
POJ 2785 4 Values whose Sum is 0 (semi-split binary search)