Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
- the sequence consists of at least two elements
- f0 and f1 are arbitrary
- fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
3 1 2 -1
3
5 28 35 7 14 21
4
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is , , , , 28.
定义 K数列:f[0]、f[1]任意,对于n > 1,f[n] = f[n-1] + f[n-2]。
题意:给定n个元素,构造最长的K数列。
思路:以为暴力枚举会T。。。记录元素个数并去重,递归构造。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <stack>
#include <algorithm>
#include <map>
#define CLR(a, b) memset(a, (b), sizeof(a))
using namespace std;
typedef long long LL;
const int MAXN = 1001;
int a[MAXN];
map<int, int> fp, tp;
int Count(int a, int b) {
int ans = 0;
if(fp[a+b])
{
fp[a+b]--; //fp[b]--;
ans = Count(b, a+b) + 1;
fp[a+b]++; //fp[b]++;
}
return ans;
}
int main()
{
int n; cin >> n; fp.clear();
for(int i = 0; i < n; i++) cin >> a[i], fp[a[i]]++;
if(fp[0] == n)
{
cout << n << endl;
return 0;
}
sort(a, a+n); int top = unique(a, a+n) - a;
int ans = 0;
for(int i = 0; i < top; i++) {
for(int j = 0; j < top; j++) {
if(i == j && fp[a[i]] == 1) continue;
fp[a[i]]--; fp[a[j]]--; //cout << Count(a[i], a[j]) << endl;
ans = max(ans, Count(a[i], a[j]) + 2);
fp[a[i]]++; fp[a[j]]++;
}
}
cout << ans << endl;
return 0;
}