Manthan, Codefest 16 D. Fibonacci-ish 暴力

D. Fibonacci-ish

题目连接:

http://www.codeforces.com/contest/633/problem/D

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

题意

给你n个数,然后让你随便取一些数出来,使得能够组成的广义fib序列最长

题解:

暴力枚举第一个数和第二个数就好了,然后再暴力往下走,开一个map,记录一下每个数还有多少个

注意回溯。

然后还得注意第一个数和第二个数是0的情况,这样的话,你在暴力枚举的时候,可能复杂度就变成n^3了

所以再开一个map<pair<int,int>,int> 记录一下你枚举了哪些数就好了,这样复杂度就不可能变成n^3了。

当然,你预先处理出第一个数是0,第二个数是0的也可以

其他的fib长度感觉不会超过100吧?

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e3+5;
int n;
map<int,int> H;
map<pair<int,int>,int>H2;
int a[maxn];
int deal(int x,int y)
{
    if(H[x+y]==0)return 0;
    H[x+y]--;
    int ans = deal(y,x+y);
    H[x+y]++;
    return ans+1;
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%d",&a[i]),H[a[i]]++;
    sort(a,a+n);
    int ans = 0;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            if(i==j)continue;
            if(H2[make_pair(a[i],a[j])])continue;
            H2[make_pair(a[i],a[j])]=1;
            H[a[i]]--;
            H[a[j]]--;
            ans=max(ans,deal(a[i],a[j]));
            H[a[i]]++;
            H[a[j]]++;
        }
    }
    cout<<ans+2<<endl;
}
    原文作者:qscqesze
    原文地址: https://www.cnblogs.com/qscqesze/p/5223580.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞