POJ 2785 4 Values whose Sum is 0 (折半搜索 )
来源:互联网 发布:淘宝苹果旗舰店靠谱吗 编辑:程序博客网 时间:2024/06/05 07:45
【题目链接】:click here~~
【题目大意】:
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 .
【思路】:当数据很大,无法进行全部搜索判断,可以采用折半搜索,将数据规模缩小一半,从而进行判断,此题,我们考虑先预处理a,b数组的和,那么只要找到满足
c[i]+d[i]=-(a[i]+b[i])条件即可。对于如何寻找,这里巧妙利用了STL的upper_bound and lower_bound我们知道upper_bound 返回的在前闭后开区间查找的关键字的上界,lower_bound返回的在前闭后开区间查找的关键字的下界,用上界减去下界即可得到区间内满足条件的个数,累加即可。
代码:
/* * Problem: POJ No.2785* Running time: 6844MS * Complier: G++ * Author: herongwei * Create Time: 8:24 2015/9/30 星期三*/ #include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;typedef long long LL;const int MAXN =4005;int a[MAXN],b[MAXN],c[MAXN],d[MAXN];int ab[MAXN*MAXN]; /// !!! maxn*maxnint n,m;LL res;int main(){ while(~scanf("%d",&n)) { memset(a,0,sizeof(a));memset(b,0,sizeof(b)); memset(c,0,sizeof(c));memset(d,0,sizeof(d)); memset(cd,0,sizeof(cd)); for(int i=0; i<n; ++i) scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]); res=0; int ll=0; for(int i=0; i<n; ++i) { for(int j=0; j<n; ++j) { ab[ll++]=a[i]+b[j]; } } sort(ab,ab+ll); for(int i=0; i<n; ++i) { for(int j=0; j<n; ++j) { int cd=-(c[i]+d[j]); res+=upper_bound(ab,ab+ll,cd)-lower_bound(ab,ab+ll,cd); } } printf("%lld\n",res); }}
0 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 (折半搜索 )
- 160_折半枚举(双向搜索) 4 Values whose sum is 0 (POJ No.2785)
- 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 折半枚举
- 4 Values whose Sum is 0 (POJ-2785) (折半枚举)
- 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 4 Values whose Sum is 0
- POJ2785-4 Values whose Sum is 0【折半搜索】
- POJ 2785 4 Values whose Sum is 0(折半枚举)
- POJ 2785 4 Values whose Sum is 0(折半枚举)
- IOS UILabe及UIFont用法总结
- Mysql的安装
- 很果断地选择了黑马
- S字首类破解补丁速查
- Power of Cryptography(二分+pow)
- POJ 2785 4 Values whose Sum is 0 (折半搜索 )
- T字首类破解补丁速查
- B字首类破解补丁速查
- C字首类破解补丁速查
- IOS控件之UITableView详解
- [Leetcode] Ugly Number
- U字首类破解补丁速查
- JavaScript权威指南_164_第17章_事件处理_17.2-注册事件处理程序-addEventListener()
- 编写函数any(s1,s2),将字符串s2中任一字符在字符串s1中第一次出现的位置作为结果返回。