POJ - 2549 -- Sumsets【折半枚举】

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
**/
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星空皓月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值