POJ 2785 4 Values whose Sum is 0 (折半搜索 )

【题目链接】: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*maxn
int 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);
    }
}


你可能感兴趣的:(poj,折半搜索)