CodeForces - 633D Fibonacci-ish —— 斐波那契数列

本文介绍了一种算法,用于从1000个整数中寻找最长的斐波那契数列子序列。通过枚举数列的前两项,并使用map记录每个数的出现次数来加速搜索过程。特别地,文章处理了大量零元素可能导致的复杂度问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

有1000个数,问能形成的最长斐波那契数列的长度

思路:

只要确定了数列的前两项,数列就已经确定了,所以可以枚举前两项,来找剩下的最长

因为数的绝对值小于1e9,斐波那契数列的增长速度很快,项数很少

用map记录了一下每个数出现的个数,方便搜索

要特判0的情况,因为0很多,就退化为n^3的复杂度了

#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
#define ll long long
#define max_ 100010
#define mod 1000000007
#define inf 0x3f3f3f3f
int n;
ll num[1010];
map<ll,int>mp;
void dfs(ll x,ll y,int &ans)
{
    ll k=x+y;
    if(mp[k])
    {
        mp[k]--;
        ans++;
        dfs(y,k,ans);
        mp[k]++;
    }
}
int main(int argc, char const *argv[]) {
    scanf("%d",&n);
    int f=0;
    for(int i=1;i<=n;i++)
    {
        scanf("%lld",&num[i]);
        mp[num[i]]++;
        if(num[i]==0)
        f++;
    }
    if(f==n)
    {
        printf("%d\n",n );
        return 0;
    }
    int maxx=f;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            if(i==j)
            continue;
            if(num[i]==0&&num[j]==0)
            continue;
            int ans=2;
            mp[num[i]]--;
            mp[num[j]]--;
            dfs(num[i],num[j],ans);
            mp[num[i]]++;
            mp[num[j]]++;
            if(ans>maxx)
            maxx=ans;
        }
    }
    printf("%d\n",maxx );
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值