Sumsets
Description
Given S, a set of integers, find the largest d such that a + b + c = d where a, b, c, and d are distinct elements of S.
Input
Several S, each consisting of a line containing an integer 1 <= n <= 1000 indicating the number of elements in S, followed by the elements of S, one per line. Each element of S is a distinct integer between -536870912 and +536870911 inclusive. The last line of input contains 0.
Output
For each S, a single line containing d, or a single line containing “no solution”.
Sample Input
5
2
3
5
7
12
5
2
16
64
256
1024
0
Sample Output
12
no solution
思路
先存a + b,然后二分查找d - c。
AC代码
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 2e6 + 5;
const ll inf = -1e18;
ll arr[maxn];
struct node{
ll x, y, dis;
node(){}
node(ll a, ll b, ll c){
x = a;
y = b;
dis = c;
}
}temp[maxn];
bool operator <(const node& a, const node& b){
return a.dis < b.dis;
}
ll max(ll a, ll b){
return a > b ? a : b;
}
int BinarySearch(node *A, int n, ll value){
int l = 0, r = n - 1;
while (r - l > 0){
int m = l + (r - l) / 2;
if (A[m].dis == value) return m;
else if (A[m].dis < value) l = m + 1;
else r = m;
}
return -1;
}
void solve(){
int n;
while (scanf("%d", &n), n){
for (int i = 0; i < n; ++i){
scanf("%lld", &arr[i]);
}
sort(arr, arr + n);
int cnt = 0;
for (int i = 0; i < n; ++i){
for (int j = i + 1; j < n; ++j){
temp[cnt++] = node(arr[i], arr[j], arr[i] + arr[j]);
}
}
sort(temp, temp + cnt);
ll ans = inf;
for (int i = n - 1; i >= 0; --i){
for (int j = n - 1; j >= 0; --j){
if (i == j) continue;
int pos = BinarySearch(temp, cnt, arr[i] - arr[j]);
if (pos == -1) continue;
if (temp[pos].x != arr[i] && temp[pos].x != arr[j] && temp[pos].y != arr[i] && temp[pos].y !=arr[j]){
ans = arr[i];
break;
}
}
if (ans != inf) break;
}
if (ans == inf) puts("no solution");
else printf("%lld\n", ans);
}
}
int main(){
solve();
return 0;
}
/**
5
1
2000000002
3000000003
5000000004
5000000006
5
0
-1
-2
-3
-4
**/