牛客2018暑假多校训练营2

比赛链接

牛客2018暑假多校训练营2

题目描述

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.

输入

3 3
3 3
1 4
1 5

输出

2
7
11

解题思路

dp

  • 状态表示:\(f[i][0/1]\) 表示行进了 \(i\) 米,且最后一步是走/跑的方案数
  • 状态计算:
    \(f[i][0]=f[i-1][0]+f[i-1][1]\)
    \(f[i][1]=f[i-k][0]\)

分析:无论是走还是跑,每秒都有一个最终状态,dp枚举的就是这个最终状态,但这个最终状态是走时,前一个状态可能是走,也可能是跑;最终状态是跑时,前一个状态只能是走~
用一个前缀和数组 \(s\) 维护 \(0\sim i\) 的所有方案数,求 \(l\sim r\) ,即 \(s[r]-s[l-1]\)

  • 时间复杂度:\(O(10^5)\)

代码

//dp
//状态表示:f[i][0/1]表示走了i米,最后是跑的(1)还是走的(0)
//状态计算:f[i][0]=f[i-1][0]+f[i-1][1]
//         f[i][1]=f[i-k][0]
#include<bits/stdc++.h>
using namespace std;
const int mod=1e9+7;
int f[100010][2],s[100010];
int q,k;
int main()
{
    scanf("%d%d",&q,&k);
    f[0][0]=1;
    for(int i=1;i<=100000;i++)
    {
        f[i][0]=(f[i][0]+f[i-1][0]+f[i-1][1])%mod;
        if(i>=k)f[i][1]=(f[i][1]+f[i-k][0])%mod;
    }
    for(int i=1;i<=100000;i++)
        s[i]=(s[i-1]+f[i][0]+f[i][1])%mod;
    while(q--)
    {
        int l,r;
        scanf("%d%d",&l,&r);
        printf("%d\n",(s[r]-s[l-1]+mod)%mod);
    }
    return 0;
}
posted @ 2021-10-02 16:52  zyy2001  阅读(29)  评论(0编辑  收藏  举报