hihoCoder 1239 Fibonacci

#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
解題思路:先打表求fib數列前25項(恰好小於10^6),然後DP
dp[i][j]表示到第i位爲止,fib數列第j項的表達方法有多少種
dp[i][1]=dp[i-1][1]
dp[i][j]=dp[i-1][j]+dp[i-1][j-1]//dp[i-1][j]表示用當前項替代i-1之前的第j項,dp[i-1][j-1]表示i-1之前的第j-1項加上當前項
一定要取模,否則溢出會WA
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <stack>
#include <deque>
#include <vector>
#include <bitset>
#include <cmath>
#include <utility>
#define Maxn 100005
#define Maxm 1000005
#define MOD 1000000007
#define lowbit(x) x&(-x)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define PI acos(-1.0)
#define make_pair MP
#define LL long long 
#define Inf (1LL<<62)
#define inf 0x3f3f3f3f
#define re freopen("in.txt","r",stdin)
#define wr freopen("out.txt","w",stdout)
using namespace std;
int fib[30];
LL doc[Maxm][26];
map<int,int> _fib;
void init()
{
	fib[1]=fib[2]=1;
	_fib[1]=1;
	for(int i=3;fib[i-1]+fib[i-2]<=100000;i++)
		fib[i]=fib[i-1]+fib[i-2],_fib[fib[i]]=i;
}
int main()
{
	init();
	int n,num,ans;
	//re;
	while(~scanf("%d",&n))
	{
		ans=0;
		memset(doc,0,sizeof(doc));
		scanf("%d",&num);
		if(num==1)
		{
			ans++;
			doc[0][1]=1;
		}
		for(int i=1;i<n;i++)
		{
			scanf("%d",&num);
			for(int j=1;j<=25;j++)
				doc[i][j]=doc[i-1][j];
			if(_fib[num])
			{
				if(num==1)
				{
					if(doc[i][1])
					//fib數列第二項
					{
						ans+=doc[i-1][1];
						ans++;
						ans%=MOD;
						doc[i][1]=(doc[i-1][1]+1)%MOD;
						doc[i][2]=(doc[i-1][1]+doc[i-1][2])%MOD;
					}
					else
					//fib數列第一項
					{
						ans++;
						doc[i][1]=(doc[i-1][1]+1)%MOD;
					}
				}
				else
				{
					ans+=doc[i-1][_fib[num]-1];//fib數列第三項之後
					ans%=MOD;
					if(doc[i][2])
						doc[i][_fib[num]]=(doc[i-1][_fib[num]]+doc[i-1][_fib[num]-1])%MOD;
				}
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章