POJ 2785: four values sum is zero

85 篇文章 0 订阅
36 篇文章 0 订阅

问题描述:

给定四个长度为n的数组A, B, C, D。 要求从每个数组中取一个数, 这样得到四个数, 并且这四个数的之和为0. 求这样组合的个数。

限制条件: 1<= n <= 4000

例如, 输入:

6
-45 -41 -36 -36 26 -32
22 -27 53 30 -38 -54
42 56 -37 -75 -10 -6
-16 30 77 -46 62 45
格式是:  数组大小

                  数组A

                   数组B

                   数组C

                   数组D

输出:

                 5

分析:

四个数列的组合数a, b, c, d总共有 n * n * n * n = n^4, 这样复杂度太大。 

如果将其对半的话, 即分为a + b + c + d = 0 ------------》c + d = -(a + b), 也就是将其分为AB 和 CD, 再考虑, 问题就会被简化。 从两个数组C, D 分别选择出两个数进行组合总共有 n * n = n^2, 这可以通过枚举出来。 然后将这n^2个数排好序, 然后用就可以采用二分搜索了。 这里可以调用lower_bound 和 upper_boud 函数解决了。

程序如下:

#include <iostream>
#include <cstdio>
#include <algorithm> // for std::upper_bound and std::lower_bound
                     //std::sort

using namespace std;

typedef long long Int64;
const int MAX_N = 4000 + 10;
int n;
int A[MAX_N], B[MAX_N], C[MAX_N], D[MAX_N];
int CD[MAX_N * MAX_N]; // store all the combinations of array C and D

int main() {
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    while(scanf("%d", &n) != EOF) {
        for(int i = 0; i < n; i++) {
            scanf("%d", &A[i]);
        }
        for(int i = 0; i < n; i++) {
            scanf("%d", &B[i]);
        }
        for(int i = 0; i < n; i++) {
            scanf("%d", &C[i]);
        }
        for(int i = 0; i < n; i++) {
            scanf("%d", &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);

        Int64 res = 0; // store the number of candidates

        for(int i = 0; i < n; i++) {
            for(int j = 0; j < n; j++) {
                int cd = -(A[i] + B[j]);
                // 取出C和D中和(存储在CD数组中)为cd的部分
                res += upper_bound(CD, CD + n * n, cd)
                       - lower_bound(CD, CD + n * n, cd);
            }
        }
        // printf long long, Apparently %lld is the most common way,
        // but that doesn't
        // work on the compiler that I'm using (mingw32-gcc v4.6.0).
        // The way to do
       // it on this compiler is: %I64d
        printf("%I64d \n", res); // printf long long int
    }
    return 0;
}
运行结果如下:


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值