当前位置: 代码迷 >> 综合 >> 上海金马五校程序竞赛网上资格赛 C Frog 【前缀和+DP】
  详细解决方案

上海金马五校程序竞赛网上资格赛 C Frog 【前缀和+DP】

热度:15   发布时间:2024-01-09 10:25:49.0

本来这个题很简单,但因为做这种取膜的题太少,犯了很傻比的错误。在这里mark一下

题面:

Description
There is a little frog called Matt. One day he comes to a river. The river could be considered as an axis. Matt is standing on the left bank now (at position 0). He wants to cross the river and reach the right bank (at position N). But Matt could only jump at most LL units, for example from 0 to L. There are N?1 rocks lying on the river equably (at position 1,2,?,N?1). The size of the rocks can be ignored, so each rock can be thought as a point on the axis. Matt can jump to a rock from the left bank or other rocks, and he can jump to the right bank from a rock or the left bank.
Now, Matt wants to know how many ways are there to cross the river. Of course, Matt could only jump forward.

Input
There are no more than 100 cases. Each case contains two integers N(2≤N≤100000)and L (1≤L≤N), denoting the position of the right bank and the distance Matt could jump most.

Output
For each test case, print the number of way to cross the river module 1e9+7.

Sample Input
3 1
4 3

Sample Output
1
7

题目大意:

有个数轴,长为N,起始点为0,每次最多可以移动L。问从0到N一共有多少种走法

大致思路:

可以通过简单的例子推出一个状态转移方程:

dp[i]=dp[i?1]+dp[i?2]+....+dp[i?l]
但是,对于每一个 dp[i] 都进行这么一个循环太过于浪费时间
所以引入一个 sum 数组,将前 i 个数字的总和统计,
然后就有 p[i]=sum[i]?sum[i?l?1]
最后扫一遍,答案就出来了
关键!!对于每次运算结果都取膜!!很重要!!!

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
const ll maxn=1e5+10;
ll p[maxn];
ll sum[maxn];
int len,num;
int main()
{while(cin>>num>>len){memset(p,0,sizeof(p));memset(sum,0,sizeof(sum));sum[0]=p[0]=p[1]=1;for(int i=1;i<=num;++i){p[i]=sum[i-1];if(i>len)p[i]=(p[i]-sum[i-len-1])%mod;sum[i]=(p[i]+sum[i-1])%mod;sum[i]%=mod;}cout<<(p[num]+mod)%mod<<endl;}return 0;
}