We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.
But, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size k.
Now Marmot wonders in how many ways he can eat between a and b flowers. As the number of ways could be very large, print it modulo1000000007 (109 + 7).
Input contains several test cases.
The first line contains two integers t and k (1 ≤ t, k ≤ 105), where t represents the number of test cases.
The next t lines contain two integers ai and bi (1 ≤ ai ≤ bi ≤ 105), describing the i-th test.
Print t lines to the standard output. The i-th line should contain the number of ways in which Marmot can eat between ai and bi flowers at dinner modulo 1000000007 (109 + 7).
3 2 1 3 2 3 4 4
6 5 5
- For K = 2 and length 1 Marmot can eat (R).
- For K = 2 and length 2 Marmot can eat (RR) and (WW).
- For K = 2 and length 3 Marmot can eat (RRR), (RWW) and (WWR).
- For K = 2 and length 4 Marmot can eat, for example, (WWWW) or (RWWR), but for example he can't eat (WWWR).
我理解题目的能力实在太差了,一个小时都没看懂题目.....真不知道我四级是怎么过的....
题意:
一个由‘R’和‘W’构成的字符串中,w只能以连续k个存在,例如k=2,长度为4合法的字符串只有 RRWW WWRR WWWW RWWR RRRR,给出两个长度值a,b,问长度为[a,b]的串中合法的字符串有多少个。dp[i]第i位有多少种字符串,当第i位选R时则dp[i]=dp[i-1],当第i位选W时则dp[i]=dp[i-k],所以转移方程为dp[i]=dp[i-1]+dp[i-k]
感悟:
虽然这个dp不难,但是还是从不断WA,不断TLE中学到了很多,预处理使得o(n^2)算法降为o(n),主要是查询的时候变为o(1)!
先附上TLE代码:
int t,k;
cin>>t>>k;
dp[0] = 1;
for(int i =1; i <= 100000+5; i++)
{
if(i < k) {
dp[i] = 1;
sum[i] = sum[i-1] +1;
}
else if(i == k)
dp[k] = 2;
else dp[i] = (dp[i-1] + dp[i - k])%mod;
}
while(t--)
{
int a,b;
//cin>>a>>b;
scanf("%d%d",&a,&b);
LL sum = 0;
for(int i = a; i <= b; i++)//这里最多会取t*(a-b)次模,相当于n^2,10^10,竟然没注意这是个o(n^2)的算法,我也是醉了QAQ
{
sum += dp[i];
sum %= mod;
}
cout<<sum<<endl;
}
AC代码
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include <algorithm>
#define LL long long
const int mod = 1e9+7;
const int maxn = 2000000+10;
using namespace std;
LL dp[maxn];
LL sum[maxn];
int main()
{
int t,k;
cin>>t>>k;
dp[0] = 1;
sum[0] = 0;
for(int i = 1; i < k; i++)
{
dp[i] = 1;
sum[i] = sum[i-1] + dp[i];
}
for(int i =k; i <= 100000+5; i++)
{
dp[i] = (dp[i-1] + dp[i - k])%mod;
sum[i] = sum[i-1] + dp[i];
sum[i] %= mod;
}
while(t--)
{
int a,b;
cin>>a>>b;
cout<<(sum[b] - sum[a-1]+mod)%mod<<endl;//注意这里我也WA了好几发,sum[b]-sum[a-1]有可能是负数,因为一开始取模了有肯能取摸 后sum[b]<sum[a-1],比如b = 10006,a = 1005,b%10006 < a%10006,所以要加个mod
}
return 0;
}
从这到简单的dp涨了不少姿势,233333