2993: Fibonacci-ish
时间限制: 2 Sec 内存限制: 256 MB
提交: 22 解决: 9
[提交][状态][讨论版]
题目描述
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
提示
In the first sample, if we rearrange elements of the sequence as -1, 2, 1, the whole sequence ai would be Fibonacci-ish.
来源
题意:输入n,再输入n个数的序列。找出符合条件的最长的斐波切纳数列(1、至少有2个元素,2、对任意个元素满足fn+2=fn+1+fn);
思路:由于ai的值有正负,所以用map来标记ai出现的次数。暴力枚举,每次枚举两个元素,然后再递归查找它之后的fn+2,每次更新最大长度,注意标记后的节点要还原,还有结果的res少了最开始的两个节点的长度。
#include<iostream>
#include<map>
#include<cstdio>
#include<cstring>
using namespace std;
map <int,int> mp;
map <pair<int,int>,int> m;
int a[1010];
int f(int x,int y)
{
if(mp[x+y]==0) return 0;
mp[x+y]--;
int tp=f(y,x+y);
mp[x+y]++;
return tp+1;
}
int main(void)
{
int n,i,j,res;
scanf("%d",&n);
for(i=0;i<n;i++) scanf("%d",&a[i]),mp[a[i]]++;
res=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j) continue;
if(m[make_pair(a[i],a[j])]==1) continue;
mp[a[i]]--;
mp[a[j]]--;
res=max(res,f(a[i],a[j]));
mp[a[i]]++;
mp[a[j]]++;
}
}
printf("%d\n",res+2);
return 0;
}