Journey

One day, Homer was bored in his house and decided to go in a journey to discover the lands of Springfield.The lands of Springfield is an infinite grid. Homer’s house is located at cell (0, 0) and his journey consistedof N steps, where each step is either move one cell right or one cell down.

Being bored already, Homer didn’t want his journey to be boring as well. He decided he won’t move inthe same direction for more than K consecutive steps. Thus, a journey is considered to be interesting iffor each K+1 consecutive steps Homer has moved in both directions.

QQ图片20200317150611.png

Figure 1: Example with N=5 and K=2 (first test case).

Given N and K, count the number of interesting journeys Homer can make. Two Journeys are considered different if for some i the ith step in the first Journey differs from that of the second Journey. Since the number can be large, print it modulo 1,000,000,007.

Input

Your program will be tested on one or more test cases. The first line of the input will be a single integer T, the number of test cases (1 ≤ T ≤ 500), followed by T test cases.Each test case will be presented on a single line containing two integers separated by a single space.The first integer will denote the number of steps in Homer’s journey N, followed by the second integer K representing the maximum number of consecutive steps Homer can take while moving in the same direction, where (0 ≤ N ≤ 1e5) and (0 ≤ K ≤ 1e5).Output For each test case,

output

a single line denoting the number of different journeys Homer can make modulo1,000,000,007.

样例输入
2
5 2
10 1
样例输出
16
2

f[i]表示走到第i步且第i+1步要改变方向时路径的数量,所以要枚举前面长度为k区间中的f[j],累加到f[i]上。起始状态f[0]=2,因为0之后有两种走法。

#include <bits/stdc++.h>

#define ll long long
using namespace std;
const int N = 1e5 + 10;
const ll MOD = 1e9 + 7;
ll f[N];
int n, k, T;

int main() {
    scanf("%d", &T);
    while (T--) {
        scanf("%d%d", &n, &k);
        if (n == 0) {
            puts("1");
            continue;
        }
        ll res = 0;
        int tot = 0;
        memset(f, 0, sizeof(f));
        f[0] = 2;
        for (int i = 1; i <= n; i++) {
            res = (res + f[i - 1]) % MOD, tot++;
            if (tot > k) res = (res + MOD - f[i - k - 1]) % MOD, tot--;
            f[i] = res;
        }
        printf("%lld\n", f[n]);
    }
    return 0;
}
发布了329 篇原创文章 · 获赞 28 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_45323960/article/details/104956646