Sumsets
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10533 | Accepted: 2863 |
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
5 2 3 5 7 12 5 2 16 64 256 1024 0
Sample Output
12 no solution
这个题的意思就是给你一个集合S,然后让你找4个数满足a+b+c=d,多种选择中找d最大的。
直接暴力找的话,算一算肯定是不行的。这个题也是哈希,先排个序,之后O(n^2)遍历一次,每两个相加按照和做下标压入哈希表中。之后在O(n^2)遍历一次d从尾开始,c从哪都行了,按照两个的差作为下标从哈希表里找符合条件的,只要找到即可输出退出即可,到最后也没有找到符合条件的就输出不可能。
因为这里是个集合,所以要注意4个数是各不相同的,我表示因为这个贡献了好多哇QAQ,忘了集合里面还有负数辣(╯‵□′)╯︵┻━┻,所以直接无脑哈希就可以了。
我这里下标取得余,发现在空间利用率最高的情况下更快呐(^o^)
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <map>
#include <queue>
#include <vector>
using namespace std;
const int inf=536870912;//处理负值
const int mod=1007;
int n;
int a[1005];
struct node
{
int x,y;
};
vector<node>head[mod];
int findx(int a,int b)
{
int y=a-b;
int x=y;
if(y<0)y+=inf;
y=y%mod;
int l=head[y].size();
int i;
for(i=0;i<l;++i)
{
if(x==head[y][i].x+head[y][i].y)
{
if(head[y][i].x!=b&&head[y][i].y!=b)
{
if(head[y][i].x!=a&&head[y][i].y!=a)return 1;
}
}
}
return 0;
}
int main()
{
int i,j;
int x;
while(~scanf("%d",&n)&&n)
{
for(i=0;i<mod;++i)head[i].clear();
node t;
for(i=0;i<n;++i)scanf("%d",&a[i]);
sort(a,a+n);
for(i=0;i<n-1;++i)
for(j=i+1;j<n;++j)
{
t.x=a[i];
t.y=a[j];
x=a[i]+a[j];
if(x<0)x+=inf;
x=x%mod;
head[x].push_back(t);
}
int flag=0;
for(i=n-1;i>=0;--i)
{
for(j=0;j<n;++j)
{
if(j==i)continue;
if(findx(a[i],a[j]))
{
flag=1;
goto xx;
}
}
}
xx:if(flag)printf("%d\n",a[i]);
else printf("no solution\n");
}
return 0;
}