Codeforces 474D Flowers (linear dp lookup rule)
D. Flowers time limit per test: 1.5 seconds memory limit per test: 256 megabytes
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 sizeK.
Now Marmot wonders in how many ways he can eatAAndBFlowers. As the number of ways cocould be very large, print it modulo 1000000007 (109 rows + rows 7 ).
Input
Input contains several test cases.
The first line contains two integersTAndK(1 digit ≤ DigitT, Bytes,KLimit ≤ limit 105), whereTRepresents the number of test cases.
The nextTLines contain two integersAIAndBI(1 digit ≤ DigitAILimit ≤ limitBILimit ≤ limit 105), describingI-Th test.
Output
PrintTLines to the standard output.I-Th line shoshould contain the number of ways in which Marmot can eatAIAndBIFlowers at dinner modulo 1000000007 (109 rows + rows 7 ).
Sample test (s) Input
3 21 32 34 4
Output
655
Note
K= 2 and length 1 Marmot can eat (
R).
K= 2 and length 2 Marmot can eat (
RR) And (
WW).
K= 2 and length 3 Marmot can eat (
RRR),(
RWW) And (
WWR).
K= 2 and length 4 Marmot can eat, for example ,(
WWWW) Or (
RWWR), But for example he can't eat (
WWWR).
One thing loves flowers. There are two colors: Red R and white W. Each time he eats white flowers, one group eats one group, and the other group eats k in a row, how many ways does the number of flowers work from ai to bi?
Question Analysis: dp [I] indicates that the length is I, which indicates the number of flowers consumed by the user. In the initial stage, dp [I] = 1 (0 <= I <k) when I is smaller than k, there is obviously only one
When I> = k, we can add a safflower to dp [I-1] or dp [I-k] with k white flowers, dp [I] = dp [I-1] + dp [I-k]
Then obtain the prefix and of the dp array. At the time of query, O (1)
#include
#include
#define ll long longint const MAX = 1e5 + 5;int const MOD = 1e9 + 7;int a[MAX];ll dp[MAX], sum[MAX];int main(){ int t, k; scanf(%d %d, &t, &k); for(int i = 0; i < k; i++) dp[i] = 1; for(int i = k; i < MAX; i++) dp[i] = (dp[i - 1] % MOD + dp[i - k] % MOD) % MOD; sum[1] = dp[1]; for(int i = 2; i < MAX; i++) sum[i] = (sum[i - 1] % MOD + dp[i] % MOD) % MOD; while(t --) { int a, b; scanf(%d %d, &a, &b); printf(%lld, (MOD + sum[b] - sum[a - 1]) % MOD); }}