牛客网暑期ACM多校训练营(第二场)A run 动态规划

链接:https://www.nowcoder.com/acm/contest/140/A
来源:牛客网
 

run

时间限制: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

题意:给Q个询问 K(代表跑步 K米/秒);每次询问到达区间【L,R】内任一点的总方法数;

每次从起点0处出发,不能连续跑步,其余时间走步1米/秒;

思路:dp[i][0] 代表第i点行走到达  dp[i][1] 代表第i点跑步到达

dp[i][1]=dp[i-k][0]+dp[i-k][1]; 

dp[i][0]=dp[i-1][0]+dp[i-1][1];

代码:

#include<bits/stdc++.h>
using namespace std;
const int M=1e5+5;
const int MO=1e9+7;
long long  dp[M][2];//到达dp[i]的方法数 0 or 1 两种方式
int main()
{
  int i,j,n,m,k;
  scanf("%d%d",&n,&k);
  dp[0][0]=1;
  for(i=1; i<M; i++)//
  {
    if(i-k>=0)//第i点 奔跑到达
      dp[i][1]=dp[i-k][0]%MO;//不能连续奔跑 前一步只能是走路到达 i-k 只有一种
      //第i点 走路到达
      dp[i][0]=(dp[i-1][1]+dp[i-1][0])%MO;//有两种方法 0/1 到达位置 i-1 ;
  }
  long long sum[M]= {0};
  for(i=1; i<=M; i++) //方法数前缀和
    sum[i]=(dp[i][1]%MO+dp[i][0]%MO+sum[i-1]%MO)%MO;
  while(n--)
  {
    int l,r;
    scanf("%d%d",&l,&r);
    long long ans=0;//求区级[L,R];
    if(l)ans =(sum[r]-sum[l-1]+MO)%MO;
    else ans=sum[r];
    printf("%lld\n",ans);
  }
}/*
3 3
3 3
0 0
1 5
 
*/

代码二 压缩空间

#include<bits/stdc++.h>
using namespace std;
const int M=1e5+5;
const int MO=1e9+7;
long long  dp[M];//到达dp[i]的方法数方式
int main()
{
  int i,j,n,m,k;
  cin>>n>>k;
  memset(dp,0,sizeof dp);
  for(i=0; i<=k; i++)
    dp[i]=1;
  dp[k]=2;
  for(i=k+1; i<M; i++)
    dp[i]=(dp[i-1]+dp[i-1-k])%MO;
  int sum[M];
  sum[0]=1;
  for(i=1; i<M; i++)
  {
    sum[i]=(sum[i-1]+dp[i])%MO;
  }
  while(n--)
  {
    int x,y;
    cin>>x>>y;
    int ans=(sum[y]-sum[x-1]+MO)%MO;
    printf("%d\n",ans);
  }


}

/*
3 3
3 3
0 2
1 5

*/

猜你喜欢

转载自blog.csdn.net/qq_41668093/article/details/81192060