codeforces 633D D. Fibonacci-ish(dfs+暴力+map)

D. Fibonacci-ish
time limit per test
3 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output

Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if

  1. the sequence consists of at least two elements
  2. f0 and f1 are arbitrary
  3. 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.

Examples
input
3
1 2 -1
output
3
input
5
28 35 7 14 21
output
4
Note

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;
}
posted @ 2016-02-27 21:44  LittlePointer  阅读(308)  评论(0编辑  收藏  举报