UVA - 10125 Sumsets (预处理 + 二分)

大体题意:

给你一个最大长度为1000的数组,让你从中找出四个不同的元素 a,b,c,d,满足  a + b + c == d

如果存在 就让d 尽可能的大,否则输出no solution

思路:

把等式变换一下  a + b == d - c;

那么我们可以先两层循环,求出所有的a + b 来,然后再两层循环枚举 d 和c,二分 a+b,看看满不满足!

这样复杂度n*n log n级别的!

注意:

因为题目要求是 四个不同元素,因此 不仅要存下 a+b 来,还要存下a和b 的位置,可以放到结构体里!

lower_bound 结构体即可!

详细见代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1000 + 10;
struct Node{
	int val;
	int a,b;
	bool operator < (const Node& rhs) const {
		return val < rhs.val;
	}

	bool operator  < (int kk) const {
		return val < kk;
	}
}p[maxn*maxn];
int x[maxn];
int main(){
	int n;
	while(scanf("%d",&n) == 1 && n){
		int cnt = 0;
		for (int i = 0 ; i < n; ++i){
			scanf("%d",&x[i]);		
		}
		for (int i = 0; i < n; ++i){
			for (int j = 0; j < n; ++j){
				if (i == j)continue;
				p[cnt].a = i;
				p[cnt].b = j;
				p[cnt++].val = x[i] + x[j];
			}
		}
		sort(p,p+cnt);
		int ans = -inf;
		for (int s = 0; s < n; ++s){
			for (int c = 0; c < n; ++c){
				if (s == c)continue;
				int m = lower_bound(p,p+cnt,x[s] - x[c]) - p;
				if (m == cnt)continue;
				while(m < cnt && p[m].val == x[s]-x[c] &&(p[m].a == s || p[m].a == c || p[m].b == s || p[m].b == c))++m;
				if (m != cnt && p[m].val == x[s] - x[c])ans = max(ans,x[s]);
			}
		}
		if (ans == -inf)printf("no solution\n");
		else printf("%d\n",ans);	
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值