http://hihocoder.com/problemset/problem/1239?sid=822524
#1239 : Fibonacci
-
6 2 1 1 2 2 3
样例输出
-
7
描述
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}
假设输入为
2 1 1 2 2 3 5 1 2 3 1 5 8
a=nums[i]统计1的个数ones
如果a=1,ones++ 。本身构成模式“1”,与前面任意一个1构成模式“1 1”,因此dp[i]=ones
如果a=2,需要前面两个1构成模式“1 1 2”,因此dp[i]=ones*(ones-1)/2
其它情况,如a=8,需找前面的所有5,构成模式“1 1 2 3 5 8”,dp[i]=前面nums[j]=5的dp[j]值的和
有了上面的分析,不难写出代码
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
int main()
{
int n, last = 1, ones = 0, res = 0;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; i++)
{
cin >> nums[i];
last = max(last, nums[i]);
}
map<int, int> fibonacci;//fibonacci存放两两前后fibonacci值 fibonacci[3] = 2;
int n1 = 2, n2 = 3, temp;
while (n2 <= last)
{
fibonacci[n2] = n1;
temp = n2;
n2 += n1;
n1 = temp;
}
map<int, int> count;//存放某个fibonacci数对应的fibonacci序列个数和
for (int i = 0; i < n; i++)
{
n1 = nums[i];
temp = 0;
if (n1 == 1)
temp = ++ones;
else if (n1 == 2)
temp = ones*(ones - 1) / 2;
else if (fibonacci.find(n1) != fibonacci.end())
temp = count[fibonacci[n1]];
if (temp > 0)
{
count[n1]+= temp;
res += temp % 1000000007;
}
}
cout << res;
return 0;
}
遗憾的是...
上面的代码并没有AC。hihocoder真不好用,写的code只提示对不对,完全不知道哪个用例错了无从改正。 测试过了好几个用例,跟别人的正确答案一样的。这是其中一个AC的答案:http://www.cnblogs.com/lessmore/p/hihocoder-1239.html
13
2 1 1 2 2 3 5 1 2 3 1 5 8
40
21
2 1 1 2 2 3 5 1 2 3 1 5 8 1 1 2 5 3 5 1 8
170
29
2 1 1 2 2 3 5 1 2 3 1 5 8 1 1 2 5 3 5 1 8 13 8 13 21 1 1 3 8
587