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;
}

 

转载于:https://www.cnblogs.com/zhgyki/p/9465324.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值