POJ 2785 4 Values whose Sum is 0
来源:互联网 发布:淘宝手机货到付款骗局 编辑:程序博客网 时间:2024/06/05 23:54
4 Values whose Sum is 0
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 -4626 -38 -10 62-32 -54 -6 45
Sample Output
5题目大意:给出4组数据,在每一组中选一个数,使4个数的和为零,问有多少种选法。
解题思路:分别求出前两组数据与后两组数据的和,然后对它们排序,利用upper_bound与lower_bound函数可以求出和为0的组数。
lower_bound从已排好序的序列a中利用二分搜索找出指向满足ai >= k的ai的最小指针,upper_bound函数返回指向满足ai > k的ai的最小指针,所以长度为n的有序序列a中k的个数可以利用以下方法求出:
upper_bound(a,a + n,k) - lower_bound(a,a + n,k)
代码如下:
#include <cstdio>#include <algorithm>#include <iostream>using namespace std;typedef long long ll;const int maxn = 4005;ll a[maxn],b[maxn],c[maxn],d[maxn],ab[maxn * maxn],cd[maxn * maxn];int main(){int i,j,k,l,n,ans;while(scanf("%d",&n) != EOF){for(i = 0;i < n;i++){scanf("%lld %lld %lld %lld",&a[i],&b[i],&c[i],&d[i]);}k = 0;for(i = 0;i < n;i++){for(j = 0;j < n;j++){ab[k] = a[i] + b[j];cd[k] = c[i] + d[j];k++;}}sort(ab,ab + k);sort(cd,cd + k);ans = 0;for(i = 0;i < k;i++){ans += upper_bound(ab,ab + k,-cd[i]) - lower_bound(ab,ab + k,-cd[i]);}printf("%d\n",ans);}return 0;}
0 0
- POJ 2785 Values whose Sum is 0
- 4 Values whose Sum is 0 POJ
- 4 Values whose Sum is 0 POJ
- 4 Values whose Sum is 0 POJ
- 4 Values whose Sum is 0 POJ
- POJ 2785 4 Values whose Sum is 0
- POJ 2785 4 Values whose Sum is 0 二分
- POJ 2785:4 Values whose Sum is 0
- POJ 2785(4 Values whose Sum is 0)
- poj 2785 4 Values whose Sum is 0
- poj 2785 4 Values whose Sum is 0 (二分+枚举)
- poj 2785 4 Values whose Sum is 0(hash)
- POJ 2785: 4 Values Whose Sum is 0
- poj 2785 4 Values whose Sum is 0
- POJ 2785 4 Values whose Sum is 0 Hash!
- poj 2785 4 Values whose Sum is 0 哈希
- POJ 2785 4 Values whose Sum is 0(二分)
- POJ 2785 4 Values whose Sum is 0 二分
- 修改非分页内存大小及禁用Null会话内存共享
- Dynamic Programming series
- JVM中对象的创建过程
- JVM内存结构
- 内存对齐的规则
- POJ 2785 4 Values whose Sum is 0
- 不要拿着别人的地图,找自己的路
- JavaWeb中的监听器
- POJ 2366 Sacrament of the sum
- java的封装
- 回家 (Standard IO)
- 数三角(triangle)
- maven test debug 方法
- 【LEETCODE】115- Distinct Subsequences [Python]