There is a straight highway with N storages alongside it labeled by 1,2,3,...,N. Bob asks you to paint all storages with two colors: red and blue. Each storage will be painted with exactly one color.
Bob has a requirement: there are at least M continuous storages (e.g. "2,3,4" are 3 continuous storages) to be painted with red. How many ways can you paint all storages under Bob's requirement?
There are multiple test cases.
Each test case consists a single line with two integers: N and M (0<N, M<=100,000).
Process to the end of input.
One line for each case. Output the number of ways module 1000000007.
4 3
3
题目链接:Click here~~
题意:
n个格子排成一条直线,可以选择涂成红色或蓝色,问至少有m 个连续格子为红色的方案数。
解释一下这个:
dp[i]=(dp[i-1]*2%mod+mod_pow(2,i-m-1,mod)-dp[i-m-1]%mod+mod)%mod;dp[i-1]*2指前i-1个已经符合条件,第i个可红可蓝,所以*2
mod_pow(2,i-m-1,mod)-dp[i-m-1]%mod指的是前i-1个还不符合条件,但是加上第i位(红色)就符合了条件的情况数。第i-m位必须为蓝(隔断),前i-m-1位可红可蓝,所以mod_pow(2,i-m-1,mod),但是要排除前i-m-1位符合条件的情况,所以-dp[i-m-1]。第i-m位的后面都是红色格子。
#include<iostream> #include<algorithm> #include<string> #include<map> #include<string.h> #include<vector> #include<cmath> #include<stdlib.h> #include<cstdio> #define ll long long using namespace std; long long dp[100010]; long long mod=1000000007; long long mod_pow(long long x,long long n,long long mod) { long long res = 1; while(n > 0) { if(n&1)res = res * x %mod; x = x * x % mod; n >>= 1; } return res; } int main() { long long n,m; while(scanf("%lld%lld",&n,&m)!=EOF) { memset(dp,0,sizeof(dp)); dp[m]=1; //当长度刚好只有m的时候,当然只有1种排法 for(int i=m+1;i<=n;i++) { dp[i]=(dp[i-1]*2%mod+mod_pow(2,i-m-1,mod)-dp[i-m-1]%mod+mod)%mod; } cout<<dp[n]%mod<<endl; } return 0; }