Sumsets

Time Limit:
1000ms
Memory limit:
65536kB
题目描述
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.
输入
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.
输出
For each S, a single line containing d, or a single line containing "no solution".
样例输入
5
2 3 5 7 12
5
2 16 64 256 10240
样例输出
12
no solution

 

解答:

 

#include <iostream>
#include <algorithm>
using namespace std;
__int64 a[1001],sum;
bool search(int l,int r,int key,int i,int j)
{
  
  while(l<=r)
  {
  int mid=(l+r)/2;//这句要放在while里面 ,因为这句话还写了两次,郁闷
   if(a[mid]==key && mid!=i && mid!=j) return true;
   else if(key<a[mid])r=mid-1;
   else  l=mid+1;
  }
  return false; 
}
int main()

 int i,j,k,n,flag;
 while(1)
 {
    scanf("%d",&n);
    if(!n) break;
    flag=0;
   
    for(i=0;i<n;i++)
    scanf("%I64d",a+i);
    if(n<4) goto end;//注意要满足个数
    sort(a,a+n); 
    for(i=n-1;i>=0;i--)
    {
   sum=a[i];
    for(j=n-1;j>=0;j--)
   {
    if(j==i) continue;
    if(a[0]+a[1]+a[j]>sum) continue;
    for(k=n-1;k>=0;k--)
    {
       if(k==i || k==j) continue;
       if(search(0,k-1,sum-a[j]-a[k],i,j))
       {
          flag=1;
          goto end;//找到后就退出所有循环,break跳不出来
     } 
    }
   }
   
  }
  end:
   if(flag)printf("%d\n",sum);
      else printf("no solution\n");
 }
    system("pause");
    return 0;
}

记:编程时应该先找出题目隐含的约束条件,并试着先把它转化成code,还有 if(n<4) goto end;记得考虑输入数据的合法性, if(a[0]+a[1]+a[j]>sum) continue;这是提高程序效率的句子,因为当最后一个数与前两个相加都大于最大的,第四个数就没有值可以取了。

posted on 2010-04-09 22:05  蓝牙  阅读(864)  评论(0编辑  收藏  举报