牛客网多校练习赛2 A 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
#include<iostream>
#include<algorithm>
#include<string>
#include<map>//int dx[4]={0,0,-1,1};int dy[4]={-1,1,0,0};
#include<set>//int gcd(int a,int b){return b?gcd(b,a%b):a;}
#include<queue>
#include<cmath>
#include<stack>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
#define ll long long
#define maxn 500005
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000") ///在c++中是防止暴栈用的
const int mod=((1e9)+7);
ll n,k,l,r;
ll dp[maxn][2];
ll sum[maxn];
/*
题目大意:一个人每秒可以走1一米,
也可选择跑k米,但跑完后必须走不能连续跑,
给定l和r,问有多少中跑步方案跑l到r的距离。

首先方案数肯定是满足前缀和性质的,即
f(l,r)=sum(r)-sum(l-1);
那么dp的思路就很清晰了,
dp[i][0]表示跑到i米最后一步是走的,
dp[i][1]表示跑到i米最后一次是跑的,
递推性质很简单,看代码即可,
然后计算个前缀和即可。

*/
int main()
{
    scanf("%lld%lld",&n,&k);
    sum[0]=0;

    for(int i=1;i<k;i++)
    {
        dp[i][0]=1;
        sum[i]=sum[i-1]+1;
    }
    sum[k]=sum[k-1]+2;
    dp[k][1]=dp[k][0]=1;
    for(int i=k+1;i<maxn;i++)
    {
        dp[i][0]=(dp[i-1][0]+dp[i-1][1])%mod;
        dp[i][1]=(dp[i-k][0])%mod;
        sum[i]=(sum[i-1] + dp[i][0]+dp[i][1])%mod;
    }
    for(int i=1;i<=n;i++)
    {
        scanf("%lld%lld",&l,&r);
        printf("%lld\n",(sum[r]-sum[l-1]+mod)%mod);///////
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37451344/article/details/81149862
今日推荐