SWJTUOJ-2364 A room Problem(easy)

来源:互联网 发布:笛子校音器软件 编辑:程序博客网 时间:2024/06/05 19:01

A room Problem(easy)

发布时间: 2017年5月7日 17:10   最后更新: 2017年5月7日 17:12   时间限制: 2000ms   内存限制: 128M

Everyday, YeahPeng walks up many stairs to the room. One Day, a problem comes to him. There are n stairs,and he can walk up stairs which is one, two, or three stairs in single step. He wants to know how many ways to reach the top.

There may be too many ways, so output the ans mod (109+7).


The first line: the number of case T(1T1000) 
Then T lines follow, each line contains one integers: n(2n1000)

For each case, out put an integer v one line -- the number of the ways mod 109+7

 复制
234
24

题意:有n阶楼梯,一次可以走一步,两步,或者三步,问一共有多少种走法,一道爬楼梯的题,第一反应是划分和排列组合,后来发现其实是一个斐波那契数列变体。斐波那契数列是前两项之和,这道题是前三项之和(注意这里楼梯是从1开始的,不是0)。

例:5阶楼梯的走法

3 22 33 1 11 3 11 1 31 2 22 1 22 2 12 1 1 11 2 1 11 1 2 11 1 1 21 1 1 1 1


思路:假如我现在站在第n阶楼梯,那么我可以从第n-3阶一下跨三步到达,也可以从第n-2阶一下跨两步到达,也可以从第n-1阶一下跨一步到达,所以到达第n阶楼梯的走法数总和等于到达第n-1阶楼梯的走法数和加上到达第n-2阶楼梯的走法数和加上到达n-3阶楼梯的走法数和,即

dp[i]=dp[i-1]+dp[i-2]+dp[i-3];//使用递归会TLE
因为数据到后面会很大,在最后输出结果时再取模一定会WA,又因为这个表达式是和式,可以对被加数先取模再相加,不会影响结果的正确性。程序开始先对dp数组打表,之后直接输出就可以了。

AC代码:

#include<iostream>#include<cstring>#include<cmath>#define ll long longusing namespace std;const int mod=1e9+7;ll dp[1005]={0};void DP(){    dp[2]=1;    dp[3]=2;    dp[4]=4;    for(int i=5;i<1005;i++)    {        dp[i]=((dp[i-1]%mod)+(dp[i-2]%mod)+(dp[i-3]%mod))%mod;    }}int main(){    int t;    cin >> t;    DP();    while(t--)    {        int n;        cin >> n;        cout << dp[n] << endl;    }    return 0;}

原创粉丝点击