2018牛客网暑期ACM多校训练营第二场 A - run(简单DP)

题目链接 https://www.nowcoder.com/acm/contest/140#question

【题目描述】
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米或跑k米,并且不能连续两秒都在跑。
当它的移动距离在[L,R]之间时,可以选择结束锻炼。
问有多少种方案结束。
10^5组询问,所有询问的k都一样 L,R≤10^5

【思路】
动态规划思想,设dp[i][0] 表示到达i位置切可以继续跑的状态有多少种方案数,dp[i][1] 表示到达i位置只能往前走的状态有多少种方案数,那么不难想到状态转移就是从dp[i][0]可以转换到dp[i+1][0]和dp[i+k][0],dp[i][1]只能转换到dp[i+1][0].每次查询的[L,R]区间对应的结果就是dp[L][0/1],dp[L+1][0/1]…dp[R][0/1],查询次数较多,要把结果转换成前缀和。

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

const int maxn=100050;
const int mod=1e9+7;

int n,q,k;
ll dp[maxn][2];
ll s[maxn];

void solve(){
    n=maxn-20;
    memset(dp,0,sizeof(dp));
    dp[0][0]=1;
    for(int i=1;i<=n;++i){
        dp[i][0]=(dp[i-1][0]+dp[i-1][1]+dp[i][0])%mod;
        if(i-k>=0) dp[i][1]=(dp[i-k][0]+dp[i][1])%mod;
    }
    memset(s,0,sizeof(s));
    for(int i=1;i<=n;++i){
        s[i]=(s[i-1]+dp[i][0]+dp[i][1])%mod;
    }
}

int main(){
    while(scanf("%d%d",&q,&k)==2){
        solve();
        while(q--){
            int le,ri;
            scanf("%d%d",&le,&ri);
            ll ans=(s[ri]-s[le-1]+mod)%mod;
            printf("%lld\n",ans);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiao_k666/article/details/81154349