poj 2785--4 Values whose Sum is 0(折半枚举)

本文详细介绍了如何通过枚举和二分查找解决POJ2785问题,即从给定的a、b、c、d四组数中各取出一个数,使它们的和为零,求这样的组合数量。通过先枚举c和d的组合,放入数组排序,然后枚举a和b的组合并从排序后的数组中使用二分查找得出结果,实现O(nlogn)的时间复杂度。

给出a, b, c, d四组数,从它们之中各取出一个数,使得这4个数的和为零,求这样组合的个数。如果一列中有相同的数字,将它们当成不同的看。

http://poj.org/problem?id=2785

数据范围大,不能O(n^4)。

先枚举出c和d的组合情况,放入数组cd,将其排序。

再枚举a和b组合的情况,并从cd中二分出结果。

这样复杂度就变成O(nlogn)

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 4000 + 10;
int n, a[maxn], b[maxn], c[maxn], d[maxn], cd[maxn * maxn];
int main(){
    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 ans = 0;
    for(int i=0; i<n; i++)
    for(int j=0; j<n; j++){
        int ab = -(a[i] + b[j]);
        ans += upper_bound(cd, cd + n * n, ab) - lower_bound(cd, cd + n * n, ab);
    }
    printf("%I64d\n", ans);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值