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;  }  











原创粉丝点击