題目大意:給出一個數字n, 接下來有n個整數 從n個數中找出四個數a、b、c、d使得 a + b + c = d。求出d最大可能是幾。
數據範圍 n <= 1000 強行枚舉的話,一共有1000^4種方式。這是必不可行的。
我們利用折半枚舉的思想, a + b = d - c
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define clr(a) memset(a, 0, sizeof(a))
#define line cout<<"------------"<<endl
typedef long long ll;
const int maxn = 2e5 + 10;
const int MAXN = 1e6 + 10;
const int INF = -0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int N = 1010;
ll n, ans;
ll a[N];
int main(){
while(scanf("%lld", &n) && n){
clr(a); ans = INF;
for(int i = 0; i < n; i++) scanf("%lld", &a[i]);
sort(a, a+n);
for(int i = n-1; i >= 0; i--){
for(int j = n-1; j >= 0; j--){
if(i == j) continue;
ll sum = a[i]-a[j];//枚舉 d - c
//查找是否有對應的 a、b 存在
for(int l = 0, r = j-1; l < r;){
if(a[l] + a[r] == sum){
ans = a[i]; break;
}
if(a[l] + a[r] > sum) r--;
else l++;
}
if(ans != INF) break;
}
if(ans != INF) break;
}
if(ans == INF) printf("no solution\n");
else printf("%lld\n", ans);
}
return 0;
}