题目来源: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;
}