POJ 2549 -- Sumsets

本文介绍了一种解决特定四数求和问题的高效算法。该算法通过预处理和二分查找技术,避免了全枚举,显著提升了计算效率。

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

题目来源:http://poj.org/problem?id=2549

给出集合S,找出元素a,b,c,d,满足a+b+c=d。

由于n的最大值为1000,不可能将a,b,c,d全部枚举出。

由于a + b = d - c 我们可以提前预处理出所有 x+y和x-y,然后进行二分查找。

为避免重复,需记录每个x和y,然后进行验证。

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
const int maxn=1010;
int n,num[maxn];
struct data {
    int x, y, u;

    bool operator<(const data &x) const {
        return (u < x.u);
    }
}b[maxn*maxn],a[maxn*maxn];
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    while (cin >> n) {
        if (n == 0)break;
        for (int i = 1; i <= n; ++i)
            cin >> num[i];
        int cnt = 0;
        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (i != j) {
                    a[++cnt].u = num[i] + num[j];
                    a[cnt].x = num[i];
                    a[cnt].y = num[j];
                    b[cnt].u = num[i] - num[j];
                    b[cnt].x = num[i];
                    b[cnt].y = num[j];
                }
            }
        }
        sort(a + 1, a + 1 + cnt);
        sort(b + 1, b + 1 + cnt);
        int ans = -1e9;
        for (int i = 1; i <= cnt; ++i) {
            int p = lower_bound(b + 1, b + 1 + cnt, a[i]) - b;
            int q = upper_bound(b + 1, b + 1 + cnt, a[i]) - b;
            if (q - p) {
                for (int j = p; j < q; ++j) {
                    if (a[i].x != b[j].x && a[i].x != b[j].y && a[i].y != b[j].x && a[i].y != b[j].y) {
                        ans = max(ans, b[j].x);
                    }
                }
            }
        }
        if (ans == -1e9)cout << "no solution" << endl;
        else cout << ans << endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值