最长斐波那契子序列(动态规划+哈希表)

最长斐波那契子序列(动态规划+哈希表)

题目

A sequence of integer numbers a1 , a2 , …, an is called a Fibonacci sequence if ai = ai-2+ai-1 for all i=3,4,…,n.
Given a sequence of integer numbers c1 , c2 , …, cm you have to find its longest Fibonacci subsequence.
Input
There are several test cases in the input. The first line of each case contains m (1 <= m <= 3,000). Next line contains m integer numbers not exceeding 109 by their absolute value.
There is a new line between each case.
Output
On the first line of each case print the maximal length of the Fibonacci subsequence of the given sequence. On the second line print the subsequence itself.
There is a new line between each case.
Sample Input
1
10
1 1 3 -1 2 0 5 -1 -1 8
Sample Output
5
1 -1 0 -1 -1

大概意思就是输入序列,求出这个序列的最长斐波那契子序列并将其输出。可同时输入多个测试用例,每个用例的第一行为该序列的长度,第二行是该序列数,每个用例用空行隔开。输出第一行是该序列的最长斐波那契子序列的长度,第二行为其斐波那契子序列。

思路

对于斐波那契数列,前面两个数字确定,序列长度确定,则该斐波那契数列便确定了。在这道题中,需要找出最大长度的斐波那契子序列并记录其前面两个数。

采用动态规划来做。数组a[ ]存放输入的序列,dp[i][j]表示以a[i]、a[j]开头的斐波那契序列的最大长度,则动态转移方程为:

	d[i][k] = d[i][j]+1		其中 k =(a[i]+a[j])在数组a[]中的下标

将dp[][]初始化为1,从后往前遍历更新方程。并创建hash表来快速查询a[i]+a[j]在数组中的位置。

先对输入的序列排序,i表示从后往前遍历,j表示从前向后遍历到i-1的位置,若a[j]+a[i]在序列中,则有d[j][i] = d[i] [a[j]+a[i]的下标]+1。然后最长斐波那契子序列的长度,并记录该最长子序列的前两个数。

若输入的序列只有一个数,则其斐波那契子序列的长度为1,输出,该数;若输入的序列为两个数,输出这两个数;若输入的序列长度大于2,但找不到三个数满足斐波那契式,则其最长的斐波那契子序列长度为2,输出该序列的前两个数即可。

代码

#include<stdio.h>
#include<algorithm> 
#include<map>       

using namespace std;

int m;              //每个用例序列的长度
int a[3005];        //存放输入序列
int dp[3005][3005]; //dp[i][j]表示以a[i]、a[j]开头的斐波那契序列的最大长度
map<int,int>mp;
map<int,int>::iterator index;

void 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值