【POJ-2785】解题报告(二分水题)
原始题目
4 Values whose Sum is 0
- Time Limit: 15000MS
- Memory Limit: 228000K
- Total Submissions: 28507
- Accepted: 8591
- Case Time Limit: 5000MS
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 \(2^{28}\) ) 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
Hint
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).
Source
Southwestern Europe 2005
题目大意
给定四个长度为n的数列,从每一个数列中抽取一个数,问和为零的共有多少种可能。
解题思路
- 预处理出前两个数列的和sum1与后两个数列的和sum2。
- 对sum1排序,二分查找sum2中每个元素的相反数,累加输出
- 注意不要用binary_search函数,而应该用upper_bound - lower_bound ,因为可能sum1数列中有多个元素值均为 -sum2[i] 。如果用binary_search 只能得到是否有,计数会少计。
解题代码
1 |
|
收获与反思
- 加深STL里三个函数应用和相互区别。
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!