SWJTUOJ-2364 A room Problem(easy)

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

 複製
2
3
4
2
4

題意:有n階樓梯,一次可以走一步,兩步,或者三步,問一共有多少種走法,一道爬樓梯的題,第一反應是劃分和排列組合,後來發現其實是一個斐波那契數列變體。斐波那契數列是前兩項之和,這道題是前三項之和(注意這裏樓梯是從1開始的,不是0)。

例:5階樓梯的走法

3 2
2 3
3 1 1
1 3 1
1 1 3
1 2 2
2 1 2
2 2 1
2 1 1 1
1 2 1 1
1 1 2 1
1 1 1 2
1 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 long
using 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章