链接:https://www.nowcoder.com/acm/contest/140/A
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld
题目描述
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
题意:一个人可以选择一次走1m或者选择一次跑k m,问从L跑到R有多少种方法;
思路:dp推导,dp[i][0]表示走i米的方法数,dp[i][1]表示跑到第i米所表示的方法数,那么到第i米走着来的所用的方法数可以由第i-1米走着来的和跑着来的方法数得到,那么第i米跑着来的方法数可以由第i-k米的方法数得到,这样就得到一个递推式:
dp[i][0]=dp[i-1][0]+dp[i-1][1]
dp[i][1]=dp[i-k];
然后我们用一个数组sum记录前缀和,那么从L到R的方法数等于sum[r]-sum[l-1],注意取余即可;
下面附上代码:
#include<bits/stdc++.h>
using namespace std;
const int mod=1000000007;
int dp[100005][2];
int sum[100005];
int n,q,k,l,r;
void solve()
{
dp[0][0]=1;
for(int i=1;i<=1e5;i++)
{
dp[i][0]=(dp[i-1][0]%mod+dp[i-1][1]%mod)%mod;
if(i>=k) dp[i][1]=dp[i-k][0]%mod;
}
for(int i=1;i<=1e5;i++)
sum[i]=(sum[i-1]%mod+dp[i][0]%mod+dp[i][1]%mod+mod)%mod;
}l;
int main(){
cin>>q>>k;
solve();
while(q--)
{
scanf("%d %d",&l,&r);
printf("%d\n",(sum[r]-sum[l-1]+mod)%mod);
}
return 0;
}
凯哥的:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
ll dp[100005][5];
ll dpp[100005];
int main()
{
ll Q,k;
while(~scanf("%lld %lld",&Q,&k)){
ll L,R;
memset(dp,0,sizeof(dp));
memset(dpp,0,sizeof(dpp));
for(ll i=1;i<=k;i++){
dp[i][1]=1;
dp[i][0]=0;
}
dp[k][0]=1;
for(ll i=1;i<=k;i++){
dpp[i]=(dp[i][1]+dp[i][0]+1000000007)%1000000007;
}
/*
dp[1][1]=1;
dp[1][3]=0;
dpp[1]=1;
dp[2][1]=1;
dp[2][3]=0;
dpp[2]=1;
dp[3][1]=1;
dp[3][3]=1;
dpp[3]=2;
*/
for(ll i=k+1;i<=100002;i++){
dp[i][1]=(dp[i-1][1]+dp[i-1][0]+1000000007)%1000000007;
dp[i][0]=dp[i-k][1];
dpp[i]=(dp[i][1]+dp[i][0]+1000000007)%1000000007;
}
//printf("----\n");
//for(int i=1;i<=7;i++){
// printf("%d ",dpp[i]);
//}
//printf("----\n");
for(ll i=2;i<=100002;i++){
dpp[i]=(dpp[i]+dpp[i-1]+1000000007)%1000000007;
}
while(Q--){
scanf("%lld%lld",&L,&R);
printf("%lld\n",(dpp[R]-dpp[L-1]+1000000007)%1000000007);
}
}
return 0;
}