poj 2549 Sumsets (枚举+二分)

来源:互联网 发布:we淘宝官方旗舰店 编辑:程序博客网 时间:2024/06/07 01:00
Sumsets
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 10026 Accepted: 2743

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


#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--)    //枚举dfor (i=0;i<=n-4 && 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");elseprintf("%d\n",ans);}return 0;}


0 0
原创粉丝点击