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

描述

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

题意:求 子序列能满足是fibonacci数列前缀的 个数。DP解法。 DP[i]代表以第i个fibonacci数结尾的子序列个数,1特殊考虑。dp[i+1]=dp[i]。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<string>
#include<limits.h>
#include<unordered_map>
#include<stack>
using namespace std;
long long dp[100001];
int main()
{
	int n;
	scanf("%d",&n);
	unordered_map<int,int> Map;
	Map[1]=1;Map[2]=2;
	int k=3,last=1,pre=2;
	while(true) {
		int t=last+pre;
		if(t>100000) break;
		Map[t]=k++;
		last=pre;
		pre=t;
	}
	int num;
	memset(dp,0,sizeof(dp));
	long long res=0;
	for(int i=0;i<n;i++) {
		scanf("%d",&num);
		if(num==1) {
			dp[1]++;
			res=(res+1)%1000000007;
		}
		else if(num==2){
			if(dp[1]>=2) {
				dp[2]=(dp[2]+(dp[1])*(dp[1]-1)/2)%1000000007;
			}
		}
		else if(Map.find(num)!=Map.end()) {
			int pos=Map[num];
			if(dp[pos-1]>0) {
				dp[pos]=(dp[pos]+dp[pos-1])%1000000007;
			}
		}
	}
	res=(res+(dp[1]*(dp[1]-1))/2)%1000000007;
	for(int i=2;i<100000&&dp[i]!=0;i++) {
		res=(res+dp[i])%1000000007;
	}
	printf("%lld\n",res);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值