1152 - 4 Values whose Sum is 0
来源:互联网 发布:人工智能 招聘 深圳 编辑:程序博客网 时间:2024/05/21 18:45
The SUM problemcan be formulated as follows: given four lists A, B, C, D ofinteger values, compute how many quadruplet (a, b, c, d ) A x B x C x D aresuch that a + b + c + d =0 . In the following, we assume that all lists have the same size n.
Input
The inputbegins with a single positive integer on a line by itself indicating the numberof the cases following, each of them as described below. This line is followedby 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 (thisvalue can be as large as 4000). We then have n linescontaining four integer values (with absolute value as large as228 )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 consecutivecases will be separated by a blank line.
For each input file, your program has to write the number quadruplets whose sumis 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 iszero: (-45, -27, 42, 30), (26, 30, -10, -46), (-32, 22, 56, -46),(-32, 30, -75,77), (-32, -54, 56, 30).
代码:
#include<iostream>
#include<algorithm>
using namespacestd;
const int maxn =4000 + 5;
int n, c, A[maxn],B[maxn], C[maxn], D[maxn], sums[maxn*maxn];
int main()
{
ios::sync_with_stdio(false);
int T;
cin>>T;
while(T--)
{
cin>>n;
for(int i = 0; i < n; i++)
{
cin>>A[i]>>B[i]>>C[i]>>D[i];
}
c = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
sums[c++] = A[i] + B[j];
}
}
sort(sums, sums+c);
long long cnt = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
cnt += upper_bound(sums,sums+c, -C[i]-D[j]) - lower_bound(sums, sums+c, -C[i]-D[j]);
}
}
cout<<cnt<<endl;
if(T)
{
cout<<"\n";
}
}
return 0;
}
解析:
为了防止超时:枚举A+B,并将结果存储在一个数组中,再枚举-C-D,在排序后的A+B数组中进行查找,求的结果。
- 1152 - 4 Values whose Sum is 0
- 1152 - 4 Values whose Sum is 0
- 1152 - 4 Values whose Sum is 0
- 4 Values whose Sum is 0 (P2785)
- 4 Values whose Sum is 0
- 4 Values whose Sum is 0
- 2785 4 Values whose Sum is 0
- 4 Values whose Sum is 0
- UVA1152-4 Values whose Sum is 0
- POJ2785 4 Values whose Sum is 0
- 哈希-4 Values whose Sum is 0
- 4 Values whose Sum is 0
- UVa1152 - 4 Values whose Sum is 0
- POJ2785 4 Values whose Sum is 0
- UVA1152 4 Values whose Sum is 0
- E - 4 Values whose Sum is 0
- poj2785(4 Values whose Sum is 0)
- POJ2785-4 Values whose Sum is 0
- Android开发之性能调优工具
- leetcode:Valid Palindrome 菜鸟解法
- 120 - Stacks of Flapjacks
- hibernate:java.math.BigInteger cannot be cast to java.lang.Long
- 714 - Copying Books
- 1152 - 4 Values whose Sum is 0
- 1442 - Cav
- 1451 - Average
- 网站加速--服务器编写篇(转)
- 计算器的实现——基础篇(一)
- jetty嵌入式 webApp开发(Simple Demo)
- 1471 - Defense Lines
- 1605 - Building for UN
- 1606 - Amphiphilic Carbon Molecules