Sumsets
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9765 | Accepted: 2659 |
Description
![](https://i-blog.csdnimg.cn/blog_migrate/d903c9a08afdf3b6dfac35b18da4660b.jpeg)
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
题意很简单,从一堆数中找到不同的四个数,注意要各不相同,a,b,c,d。满足a+b+c=d。输出满足条件的最大的那个d。
很明显要变成a+b=d-c这样的形式。然后一开始自己搞成一个O(n^2)的哈希,结果可能是因为map开的太大了?不清楚。然后自己不报希望地搞O(n^3),居然过了。。。。而且16ms。。。难以置信,只能理解为数字越多的话,就一定会有结果吧。
最后,注意负数的情况。
代码:
#pragma warning(disable:4996)
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstring>
#include <vector>
#include <string>
#include <time.h>
#include <cmath>
#include <queue>
#include <map>
using namespace std;
typedef long long ll;
#define INF 0x3fffffffffffffff
const int maxn = 1002;
int n, k;
ll val[maxn];
void input()
{
int i;
for (i = 0; i < n; i++)
{
scanf("%lld", &val[i]);
}
}
void solve()
{
sort(val, val + n);
k = unique(val, val + n) - val;
int d, f;
int lef, rig;
ll maxn = -INF;
for (d = k - 1; d >= 0; d--)
{
for (f = k - 1; f >= 0; f--)
{
if (val[d] == val[f])continue;
lef = 0;
rig = k - 1;
ll t = val[d] - val[f];
while (lef < rig)
{
ll s = val[rig] + val[lef];
if (s == t)
{
if (val[rig] != val[d] && val[rig] != val[f] && val[lef] != val[d] && val[lef] != val[f])
{
printf("%lld\n", val[d]);
return;
}
rig--;
lef++;
}
else if (s > t)
{
rig--;
}
else
{
lef++;
}
}
}
}
if (maxn == -INF)
{
printf("no solution\n");
}
else
{
printf("%lld\n", maxn);
}
}
int main()
{
//freopen("i.txt", "r", stdin);
//freopen("o.txt", "w", stdout);
while (scanf("%d", &n) != EOF)
{
if (n == 0)
break;
input();
solve();
}
//system("pause");
return 0;
}