2993: Fibonacci-ish
Time Limit: 2 Sec Memory Limit: 256 MB
Submit: 46 Solved: 19
[Submit][Status][Web Board]
Description
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.
Input
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).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Sample Input
3
1 2 -1
Sample Output
3
HINT
In the first sample, if we rearrange elements of the sequence as -1, 2, 1, the whole sequence ai would be Fibonacci-ish.
解析:起先以为是思维题,或者是贪心。但是看到n<=1000,就觉得应该是暴力了
每次枚举两个数,去寻找这两个数的和在不在数列里,在则继续寻找。特例:都是0的情况下,要特判,不然时间n^3会超时。
具体看代码;
#include<bits/stdc++.h>
using namespace std;
#define ee exp(1)
#define pi acos(-1)
#define mod 1000000007
#define inf 0x3f3f3f3f
#define ll long long
#define ull unsigned long long
#define mem(a,b) memset(a,b,sizeof(a))
int gcd(int a,int b){return b?gcd(b,a%b):a;}
const int maxn=1e3+5;
ll a[maxn];
map<ll,int> mp;
int main()
{
int n;
scanf("%d",&n);
mp.clear();
ll maxx=-1,res=0;
for(int i=0; i<n; i++)
{
scanf("%lld",&a[i]);
maxx=max(a[i],maxx);
if(a[i]==0)res++;
mp[a[i]]++;
}
ll ans=2;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(i==j)continue;
if(a[i]==0&&a[j]==0)continue;
ll x=a[i],y=a[j],cnt=2;
vector<ll> ve;
ve.clear();
ve.push_back(x);
ve.push_back(y);
mp[x]--;
mp[y]--;
while(x+y<=maxx&&mp[x+y]>0)
{
ll t=x+y;
mp[t]--;
ve.push_back(t);
x=y;
y=t;
cnt++;
}
for(int k=0; k<ve.size(); k++)
mp[ve[k]]++;
ans=max(ans,cnt);
}
}
printf("%lld\n",max(ans,res));
return 0;
}