(第二場)A Run 【動態規劃】
鏈接:https://www.nowcoder.com/acm/contest/140/A
題目描述:
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.
案例
輸入:
3 3 3 3 1 4 1 5
輸出:
2 7 11
大概題意:
小白喜歡運動,他每秒可以走一米或者跑K米,有Q次查詢,每次查詢求跑0 ~ 【L,R】米的方案數;
思路:
一開始看到這道題想著是道規律題,結果花時間列數據找規律。。。
果然還是too young too simple,師兄花了短短的時間AC之後在群裏丟給我們八個字“記憶化搜索,過了”。
想了那麽多,這就是道純粹的DP了啊,關鍵在於分開跑和走的方案,不能連續跑
狀態:
dp[i][0] 走 i meters 的方案數
dp[i][1] 跑 i meters 的方案數
轉移方程:
dp[i][0] = dp[i-1][1] + dp[i-1][0];
dp[i][1] = dp[i-k][0] (註意題目條件:不能連續跑,有隊友一直卡在60%這裏的原因)
!!!更新dp值的同時也要更新前綴和sum[i] (用於最後求答, 本人傻傻的還在後面查詢的時候才計算前綴和,一直T)!!!
AC code:
#include <cstdio> #include <iostream> #include <cstring> #define mod 1000000007 using namespace std; const int maxk = 100005; int Q, k; long long int dp[maxk][2], sum[maxk]; int main() { scanf("%d%d", &Q, &k); for(int i = 0; i < k; i++) { dp[i][0] = 1; dp[i][1] = 0; if(i > 0) sum[i] = sum[i-1] + dp[i][0]+dp[i][1]; } dp[k][1] = 1; sum[k] = sum[k-1] + dp[k][1]; for(int i = k; i < maxk; i++) { dp[i][0] = ((dp[i-1][0] + dp[i-1][1]))%mod ; dp[i][1] = dp[i-k][0]; sum[i] = sum[i-1]+dp[i][0]+dp[i][1]; } while(Q--) { int L, R; long long int ans = 0; scanf("%d%d", &L, &R); ans =(sum[R] - sum[L-1] + mod)%mod; printf("%lld\n", ans); } return 0; }
(第二場)A Run 【動態規劃】