uva10125 Sumsets
来源:互联网 发布:淘宝客服服务态度培训 编辑:程序博客网 时间:2024/05/23 01:16
Sumsets
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
52 3 5 7 1252 16 64 256 10240
Output for Sample Input
12no solution
题目意思很容易理解:
给出很多数字的个数n以0结尾,在给出的n个数中找出abcd使得a+b+c=d,如果能找到则输出d,否则输出no solution
最简单的暴力 会超时
所以我们要想方设法的减少循环层数或者循环次数,
a+b+c = d
那么a+b=d-c
这不是简单的等式变形
而是意味着我们循环的次数减少了。
我们对于d和c分别用一层循环,
对于a+b只用一层循环。
代码如下:
#include <cstdio> #include <algorithm> using namespace std; int a[1010]; int main () { int n; while(scanf("%d",&n),n) { for(int i = 0; i < n; i++) scanf("%d",&a[i]); sort(a,a+n); int f = 0; for(int i = n-1; i >= 0; i--) { for(int j = n-1; j >= 0; j--) if(i!=j) { int t = a[i]-a[j]; for(int l = 0, k = j-1; l<k;) { if(a[l]+a[k]==t) {f = 1; break;} else if(a[l]+a[k]>t) k--; else l++; } if(f) break; } if(f) {printf("%d\n",a[i]); break;} } if(f==0)printf("no solution\n"); } return 0; }
- uva10125 - Sumsets
- uva10125 Sumsets
- Sumsets Uva10125 poj
- [哈希]Sumsets uva10125
- UVa10125--Sumsets(折半搜索)
- Uva10125/POJ2549——Sumsets(中途相遇法,hash)
- uva10125
- UVA10125
- Sumsets
- Sumsets
- Sumsets
- Sumsets
- Sumsets
- Sumsets
- UVA10125和集
- uva10125 (中途相遇法)
- 10125 - Sumsets(*****)
- 10125 - Sumsets
- Unsupported compiler 'com.apple.compilers.llvmgcc42' selected for architecture 'armv7'
- [codility]Abs-distinct
- poj 2955 区间dp 括号匹配
- [codility]Binary-gap
- UVA - 11384 Help is needed for Dexter
- uva10125 Sumsets
- 数据库同步和使用JSONObject让Java Bean“原地满状态复活”
- [codility]Equi
- java中参数数量可变的方法
- 第一个struts2程序
- [codility]Max-profit
- assert的用法
- java 反射机制
- [codility]Tree-height