题意:给出一个数集,问其中是否存在a,b,c,d满足a+b+c=d,输出最大的d
理论学习:http://blog.youkuaiyun.com/doc_sgl/article/details/12462151
http://tech-wonderland.net/blog/summary-of-ksum-problems.html
也可以将问题转化为a+b=d-c,将左侧计算出之后,枚举右边用Hash解决
可以参考:http://wingszero.blogbus.com/logs/80205824.html
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,data[1005];
int main ()
{
while (scanf("%d",&n),n)
{
int ans,i;
bool flag=true;
for (i=0;i<n;i++)
scanf("%d",&data[i]);
sort(data,data+n);
int sz = unique(data,data+n)-data; //去重
n=sz;
for (int d=n-1;d>=0 && flag;d--) //枚举d
for (i=0;i<n-3 && flag;i++) //注意因为有负数存在,需要扫完全部
{
int head=i+1,tail=n-1; //从首尾两个方向扫描
while (head<tail)
{
int tmp=data[i]+data[head]+data[tail];
if (tmp==data[d])
{
if (i==d || head==d || tail==d) break;
flag=false;
ans=tmp;
break;
}
else if (tmp>data[d]) tail--;
else head++;
}
}
if (flag)
printf("no solution\n");
else
printf("%d\n",ans);
}
return 0;
}