poj2785(4 Values whose Sum is 0)
来源:互联网 发布:java服务器 编辑:程序博客网 时间:2024/05/21 10:05
Language:
4 Values whose Sum is 0
Time Limit: 15000MS Memory Limit: 228000KTotal Submissions: 19972 Accepted: 5953Case 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 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
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
题目意思很简单明了,就是从四个数列中各取一个数,使四个数的和为0,求共有多少种方法?
可以直接的四个for循环,但是显然很不高效。把它们分成AB和CD再考虑,就可以快速求解。大致思路是把C、D中的数字枚举出来,排好序,为了使总和为0则需要从C、D中取出c+d=-a-b,可以用二分查找,时间复杂度为O(n^2logn)。
AC代码:
#include<iostream>#include<cstdio>#include<algorithm>using namespace std;#define maxn 4005int A[maxn],B[maxn],C[maxn],D[maxn];int CD[maxn*maxn];int main(){ int n; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%d%d%d%d",&A[i],&B[i],&C[i],&D[i]); } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ CD[i*n+j]=C[i]+D[j]; } } sort(CD,CD+n*n); long long res=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ int cd=-(A[i]+B[j]); res+=upper_bound(CD,CD+n*n,cd)-lower_bound(CD,CD+n*n,cd); } } printf("%lld\n",res); return 0;}
0 0
- POJ2785 4 Values whose Sum is 0
- POJ2785 4 Values whose Sum is 0
- poj2785(4 Values whose Sum is 0)
- POJ2785-4 Values whose Sum is 0
- poj2785 4 Values whose Sum is 0
- POJ2785-4 Values whose Sum is 0
- POJ2785-Values whose Sum is 0
- POJ2785:4 Values whose Sum is 0(二分)
- POJ2785 4 Values whose Sum is 0 【枚举】
- POJ2785 4 Values whose Sum is 0(二分)
- POJ2785——4 Values whose Sum is 0
- Poj2785 (4 Values whose Sum is 0)
- POJ2785-4 Values whose Sum is 0【折半搜索】
- poj2785 4 Values whose Sum is 0 双向搜索
- POJ2785:4 Values whose Sum is 0(二分+暴力)
- POJ2785 -- 4 Values whose Sum is 0(折半枚举)
- POJ2785 4 Values whose Sum is 0(暴力二分查找)
- POJ2785 4 Values whose Sum is 0(二分的力量)
- RxJava变换操作符:.concatMap( )与.flatMap( )的比较
- 常用的el表达式
- EventBus的用法
- grep的"与"和"或"
- 开博第一篇
- poj2785(4 Values whose Sum is 0)
- Android 命名规范 (提高代码可以读性)
- hdu1325Is It A Tree?(并查集)
- 【HDU】1576 - A/B(扩展欧几里得)
- Bayesian Linear Regression : R Language
- Qt 中的字体
- SAP PP模块—事务代码
- 对称 非对称 加密算法在网络通信中的应用
- linux命令nohup详解