您的位置:首页 > 其它

hihocoder 1239 Fibonacci(微软2016校园招聘9月在线笔试)

2017-02-07 18:52 423 查看

#1239 : Fibonacci

时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

Given a sequence {an}, how many non-empty sub-sequence of it is a prefix of fibonacci sequence.

A sub-sequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

The fibonacci sequence is defined as below:

F1 = 1, F2 = 1

Fn = Fn-1 + Fn-2, n>=3

输入

One line with an integer n.

Second line with n integers, indicating the sequence {an}.

For 30% of the data, n<=10.

For 60% of the data, n<=1000.

For 100% of the data, n<=1000000, 0<=ai<=100000.

输出

One line with an integer, indicating the answer modulo 1,000,000,007.

样例提示

The 7 sub-sequences are:

{a2}

{a3}

{a2, a3}

{a2, a3, a4}

{a2, a3, a5}

{a2, a3, a4, a6}

{a2, a3, a5, a6}

样例输入
6
2 1 1 2 2 3

样例输出
7


题意:给你一串数字序列,求出该序列的子序列与斐波那契数列前缀相同的序列的个数。

思路:很明显的dp。用dp[i][j]表示原序列前i个数字与斐波那契数列前j个数字序列匹配的序列总数。转移方程是:

if(a[i]==f[j])
{
if(a[i]==1)
dp[i][1]=(dp[i][1]+1)%mod;
if(dp[i-1][j-1]!=0)
dp[i][j]=(dp[i][j]+dp[i-1][j-1]+dp[i-1][j])%mod;
else
dp[i][j]=dp[i-1][j];
}
else
dp[i][j]=(dp[i][j]+dp[i-1][j])%mod;

详见代码:

#include <iostream>
#include<string.h>
#include<algorithm>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef long long ll;
const int mod=1e9+7;
int f[50];
int dp[1000010][50]= {{0}};
int main()
{
f[1]=f[2]=1;
for(int i=3; i<=30; i++)
f[i]=f[i-1]+f[i-2];
int n;
cin>>n;
for(int i=1; i<=n; i++)
{
int t;
scanf("%d",&t);
for(int j=1; j<=30; j++)
if(t==f[j])
{
if(t==1)
dp[i][1]=(dp[i][1]+1)%mod;
if(dp[i-1][j-1]!=0)
dp[i][j]=(dp[i][j]+dp[i-1][j-1]+dp[i-1][j])%mod;
else
dp[i][j]=dp[i-1][j];
}
else
dp[i][j]=(dp[i][j]+dp[i-1][j])%mod;
}
int ans=0;
for(int i=1; i<=30; i++)
ans=(ans+dp
[i])%mod;
cout<<ans<<endl;
/*
for(int i=1; i<=n; i++)
{
for(int j=1; j<=30; j++)
cout<<dp[i][j]<<' ';
cout<<endl;
}*/
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm