POJ2549-Sumsets

来源:互联网 发布:东吴证券怎么样 知乎 编辑:程序博客网 时间:2024/06/05 19:02

Sumsets
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 11349 Accepted: 3119

Description

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

Sample Output

12no solution

Source

Waterloo local 2001.06.02


题意:给你n个数,问能不能找出4个数,使得a+b+c=d,若有,找出最大的d

解题思路:移项后a+b=d-c,可以先组合出所有a+b和d-c的可能,然后将d-c所有的可能根据它们的值进行排序,暴力枚举a+b的组合,然后二分查找d-c中是否有


#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <algorithm>#include <cmath>#include <queue>#include <vector>#include <set>#include <stack>#include <map>#include <climits>using namespace std;#define LL long longconst int INF=0x3f3f3f3f;int a[1005],n;struct node{    int l,r,val;} x[1000009],y[1000009];bool cmp(node a,node b){    return a.val<b.val;}int main(){    while(~scanf("%d",&n)&&n)    {        for(int i=1; i<=n; i++) scanf("%d",&a[i]);        sort(a+1,a+1+n);        int flag=0,ma=-INF,cnt1=0,cnt2=0;        for(int i=1; i<=n; i++)            for(int j=i+1; j<=n; j++)                x[cnt1].l=i,x[cnt1].r=j,x[cnt1++].val=a[i]+a[j];        for(int i=1; i<=n; i++)            for(int j=n; j>=1; j--)                if(i!=j) y[cnt2].l=i,y[cnt2].r=j,y[cnt2++].val=a[j]-a[i];        sort(y,y+cnt2,cmp);        for(int i=0; i<cnt1; i++)        {            int l=0,r=cnt2-1,ans=-1;            while(l<=r)            {                int mid=(l+r)>>1;                if(y[mid].val>x[i].val) r=mid-1;                else if(y[mid].val<x[i].val) l=mid+1;                else {r=mid-1,ans=mid;}            }            if(ans!=-1)            {                while(1)                {                    if(y[ans].l==x[i].l||y[ans].r==x[i].r||y[ans].l==x[i].r||y[ans].r==x[i].l)                    {                        ans++;                        if(y[ans].val!=y[ans-1].val||ans==cnt2) break;                        else continue;                    }                    ma=max(ma,a[y[ans].r]);                    flag=1;                    ans++;                    if(y[ans].val!=y[ans-1].val||ans==cnt2) break;                }            }        }        if(!flag) printf("no solution\n");        else printf("%d\n",ma);    }    return 0;}