01串 动态规划初级

描述

ACM的zyc在研究01串,他知道某一01串的长度,但他想知道不含有“11”子串的这种长度的01串共有多少个,他希望你能帮帮他。

注:01串的长度为2时,有3种:00,01,10。

输入
第一行有一个整数n(0<n<=100),表示有n组测试数据;
随后有n行,每行有一个整数m(2<=m<=40),表示01串的长度;
输出
输出不含有“11”子串的这种长度的01串共有多少个,占一行。
样例输入
2
2
3
样例输出
3
5


分析:

长度为n的不含‘11’的‘01’子串的由来:

由长度为n-1的01子串加上0或者1组成长度为n的01子串

1.

加上0的情况:  n-1位是什么都不会出现11子串 , 即dp[n-1]

2.

加上1的情况: n-1位不能是1,只能是0,所以,所有的情况由长度为n-2的情况决定

即dp[n-2]


综合上面两种情况,dp[n] = dp[n-1]+dp[n-2]





#include <iostream>  
#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#include <cmath>  
#include <vector>  
#include <set>  
#include <map>  
#include <stack>  
#include <string>  
using namespace std;  

int main()  
{  
    int n;
    cin >> n;
    int a[41];
    a[1] = 2;
    a[2] = 3;
    for(int i = 3;i <= 40;i++)
    	a[i] = a[i-1]+a[i-2];
    while(n--)
    {
    	int m;
    	cin >> m;
        cout << a[m] << endl;
    }
    return 0;  
}










猜你喜欢

转载自blog.csdn.net/lidafoye/article/details/77651966