題意:
給你一個整數集合,要求你從中找出一個最大的d,使得a+b+c=d,其中a,b,c,d都是集合s中的不同元素
分析:
如果暴力的話O(N^4),但是可以使用二分解決,就是美劇a+b後對其結果排序,接着枚舉d-c如果二分查找a+b的結果中存在a+b = d-c,那麼這個d就是一個解
時間複雜度O(N^2*log(N*N))
Code:
#include <set>
#include <map>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <cstdio>
#include <bitset>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
#define DIR 4
#define DIM 2
#define STATUS 2
#define MAXN 1000000 + 10
#define oo (~0u)>>1
#define INF 0x3F3F3F3F
#define REPI(i, s, e) for(int i = s; i <= e; i ++)
#define REPD(i, e, s) for(int i = e; i >= s; i --)
static const double EPS = 1e-5;
typedef struct Node_ {
long long sum, each;
}Node;
Node s[MAXN];
long long val[MAXN], arr[MAXN];
void input(int n)
{
REPI(i, 1, n) {
scanf("%lld", &val[i]);
}
}
int valid(long long a, long long b, long long c, long long d)
{
if( a == b || a == c || a == d ) {
return 0;
}
if( b == c || b == d || c == d ) {
return 0;
}
return 1;
}
inline int cmp(const Node &a, const Node &b)
{
return a.sum < b.sum;
}
long long process(int n)
{
int idx = 0;
REPI(i, 1, n) {
REPI(j, i+1, n) {
if( val[i] == val[j] ) {
continue;
}
s[idx].each = val[i];
s[idx ++].sum = val[i]+val[j];
}
}
sort(s, s+idx, cmp);
REPI(i, 0, idx-1) {
arr[i] = s[i].sum;
}
long long rst = -INF;
REPI(i, 1, n) {
REPI(j, 1, n) {
long long max_one = val[i], min_one = val[j];
if( max_one < min_one ) {
swap(max_one, min_one);
}
else if( max_one == min_one ) {
continue;
}
int m = lower_bound(arr, arr+idx, max_one-min_one)-arr;
if( arr[m] != max_one-min_one ) {
continue;
}
if( !valid(max_one, min_one, s[m].each, s[m].sum-s[m].each) ) {
continue;
}
rst = max(rst, val[i]);
}
}
return rst;
}
void ouput(long long rst)
{
if( -INF == rst ) {
printf("no solution\n");
return;
}
printf("%lld\n", rst);
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int n;
while( scanf("%d", &n) && n ) {
input(n);
ouput(process(n));
}
return 0;
}