codeforces 633D D. Fibonacci-ish(dfs+暴力+map)
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.
题意:给一个数组,问能组成斐波拉契数列的最大长度是多少;
思路:用map记录这个数是否出现以及出现了几次,用过一次-1,dfs寻找最大长度,注意开始的两个都为0的情况,否则会超时,还有我把b开成全局变量一直wa,wa到哭啊啊啊,最后改成局部变量就过了;
AC代码:
#include <bits/stdc++.h>
using namespace std;
long long a[1005];
int n,vis[1005];
map<long long,int>mp;
int ans=2;
int dfs(long long x,long long y,int num)
{
long long b=x+y;
if(mp[b]){
mp[b]--;
dfs(y,b,num+1);
mp[b]++;
return 0;
}
ans=max(ans,num);
return 0;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%I64d",&a[i]);
mp[a[i]]++;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(i!=j)
{
if(a[i]==0&&a[j]==0)
{
ans=max(ans,mp[0]);
}
else {
mp[a[i]]--;
mp[a[j]]--;
dfs(a[i],a[j],2);
mp[a[j]]++;
mp[a[i]]++;
}
}
}
}
cout<<ans<<"\n";
return 0;
}

浙公网安备 33010602011771号