POJ2785 4 Values whose Sum is 0(暴力二分查找)
来源:互联网 发布:淘宝店铺ip地址怎么查 编辑:程序博客网 时间:2024/05/18 20:36
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 .
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 .
For each input file, your program has to write the number quadruplets whose sum is zero.
6-45 22 42 -16-41 -27 56 30-36 53 -37 77-36 30 -75 -4626 -38 -10 62-32 -54 -6 45
5
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).
思路:
题目是要求四个数相加之和为零, 我们可以两 两相加, 这样的话就变成是求两个数之和为0了,再进一步想就是在另一个数组中找相反数,利用low_bound
()和up_bound可以快速的二分查找。
#include<iostream>#include<cstdio>#include<algorithm>using namespace std;const int mx = 4050;int a[mx], b[mx], c[mx], d[mx];int n, sum1[mx * mx], sum2[ mx * mx]; void slove(){ int cnt =0, nn = n * n; sort(sum1, sum1 + nn); for(int i = 0; i < nn; i++){ cnt += upper_bound(sum1, sum1+ nn, -sum2[i]) - lower_bound(sum1, sum1+ nn, -sum2[i]); //记得负号 } cout<<cnt<<endl; }int main(){while(scanf("%d", &n) != EOF){for(int i = 0; i < n; i++)scanf("%d%d%d%d", &a[i], &b[i], &c[i], &d[i]);int c1 = 0, c2 = 0; for(int i =0; i < n; i++)for(int j =0; j < n; j++){sum1[c1++] = a[i] + b[j];sum2[c2++] = c[i] + d[j];}slove();}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(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 双向搜索
- 关于this kernel requires an x86-64 cpu but only detected an i686 cpu unable to boot please use a kern
- savon调用WebService服务
- acm之路
- 图的深搜
- android优化-UI优化总结
- POJ2785 4 Values whose Sum is 0(暴力二分查找)
- SpringMVC 和Struts2的区别
- Linux编译内核模块
- weblogic控制台密码忘记解决方法
- K:Tcp/Ip三次握手与四次挥手
- 复习三种最基本的排序算法
- STM32 SPI NSS 作用
- printf重定向<达到向向服务器写日志效果>
- 移动安全大讲堂第二讲:整体解决方案之APP安全评估