POJ 2549:Sumsets

来源:互联网 发布:RBF神经网络算法 编辑:程序博客网 时间:2024/06/07 02:52

Sumsets
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 9765 Accepted: 2659

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

题意很简单,从一堆数中找到不同的四个数,注意要各不相同,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 0x3fffffffffffffffconst 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;}

0 0
原创粉丝点击