例题 8-3 UVA - 1152 4 Values whose Sum is 0(和为0的4个值)(二分枚举)

本文介绍了一种解决四个数组中寻找元素组合使和为零的问题的方法。通过预处理两个数组的所有可能组合并排序,然后对另外两个数组进行遍历,使用二分查找来寻找匹配的元素组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

给你4个n 元素的集合ABCD,要求分别从中选取一个元素abcd使得a + b + c + d = 0问有多少种选法!

思路:

先把A数组和B数组所有的组合情况都记录到tmp数组,排序,然后枚举C数组和D数组,取相反数,然后二分枚举tmp数组中值,

取上界upper_bound 和取下界 lower_bound 做差即可!

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 5000 + 5;
int a[maxn],b[maxn],c[maxn],d[maxn];
int tmp[maxn*maxn];
int main(){
    int T,cnt2 = 0;
    scanf("%d",&T);
    while(T--){
        int n,cnt=0;
        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)
                tmp[cnt++] = a[i] + b[j];
        sort(tmp,tmp+cnt);
        int ans = 0;
        for (int i = 0; i < n; ++i){
            for (int j = 0; j < n; ++j){
                int k = -c[i]-d[j];
                int pos1 = upper_bound(tmp,tmp+cnt,k) - tmp;
                int pos2 = lower_bound(tmp,tmp+cnt,k) - tmp;
                ans += pos1-pos2;
            }
        }
        if (cnt2++)printf("\n");
        printf("%d\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值