run (简单DP)

链接: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;
}

猜你喜欢

转载自www.cnblogs.com/zhgyki/p/9465324.html
run
今日推荐