1. 程式人生 > >run (簡單DP)

run (簡單DP)

%d contest span max blank nbsp nts type different

鏈接:https://www.nowcoder.com/acm/contest/140/A
來源:牛客網

題目描述
White Cloud is exercising in the playground.
White Cloud can walk 1 meters or run k meters per second.
Since White Cloud is tired,it can’t run for two or more continuous seconds.
White Cloud will move L to R meters. It wants to know how many different ways there are to achieve its goal.


Two ways are different if and only if they move different meters or spend different seconds or in one second, one of them walks and the other runs.

輸入描述:
The first line of input contains 2 integers Q and k.Q is the number of queries.(Q<=100000,2<=k<=100000)
For the next Q lines,each line contains two integers L and R.(1<=L<=R<=100000)


輸出描述:
For each query,print a line which contains an integer,denoting the answer of the query modulo 1000000007.
示例1
輸入
3 3
3 3
1 4
1 5
輸出
2
7
11

題意:一個人從0坐標開始,1秒可以走一步或者跑k步,但是不能連續跑,問跑到 [ l,r ]這個區間的方法數;

題解:dp做法,dp[ i ] [ 0/1] 表示到 i 這裏的種數,0表示走,1表示跑

初始化dp[ 0 ][ 0 ] 為1;

遞推公式:dp[i][0]=dp[i-1][0]+dp[i-1][1];

dp[i][1]=dp[i-k][0];

代碼:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define mod 1000000007
#define N 100005
int dp[N][2],l,r,q,k;
int s[N];
int main()
{
    ios_base::sync_with_stdio(0); cin.tie(0);
    memset(s,0,sizeof(s));
    dp[0][0]=1;
    cin>>q>>k;
    for(int i=1;i<=N;i++)
    {
        dp[i][0]=(dp[i-1][0]+dp[i-1][1])%mod;
        if(i>=k)dp[i][1]=dp[i-k][0];
        s[i]=(s[i-1]+dp[i][0]+dp[i][1])%mod;
    }
    while(q--)
    {
        cin>>l>>r;
        cout<<(s[r]-s[l-1]+mod)%mod<<endl;//+mod防止出現負數
    }
    return 0;
}

也可以用記憶化搜索寫:

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1e5+7;
const int mod = 1e9+7;
long long dp[maxn][2];
long long ans[maxn];
int q,k,n,m;

//flag 1 : 可以跑
long long dfs(int n,bool flag)
{
    if(n == 0) return 1;
    if(n < 0) return 0;

    if(dp[n][flag]) return dp[n][flag];

    if(flag){
        dp[n][flag] = (dfs(n-1,1) + dfs(n-k,0) )%mod;
        return dp[n][flag];
    }else{
        dp[n][flag] = dfs(n-1,1);
        return dp[n][flag];
    }
}

int main()
{
    int st = 1;
    scanf("%d%d",&q,&k);
    for(int i=0;i<q;i++){
        scanf("%d%d",&n,&m);
        dfs(m,1);
        for(;st<=m;st++){
            ans[st] = (ans[st-1] + dp[st][1])%mod;
        }
        printf("%lld\n",(ans[m] - ans[n-1] + mod)%mod );
    }
    return 0;
}

run (簡單DP)