標籤:lock number one ring The hat ISE note time
標籤 : 動態規劃
題目描述
Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the 0 key, the 1 key and the backspace key.
To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:
The 0 key: a letter 0 will be inserted to the right of the string.
The 1 key: a letter 1 will be inserted to the right of the string.
The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.
Sig has launched the editor, and pressed these keys N times in total. As a result, the editor displays a string s. Find the number of such ways to press the keys, modulo \(10^9+7\).
Constraints
1≤N≤5000
1≤|s|≤N
s consists of the letters 0 and 1.
Partial Score
400 points will be awarded for passing the test set satisfying 1≤N≤300.
輸入
The input is given from Standard Input in the following format:
N
s
輸出
Print the number of the ways to press the keys N times in total such that the editor displays the string s in the end, modulo 109+7.
範例輸入
3
0
範例輸出
5
提示
We will denote the backspace key by B. The following 5 ways to press the keys will cause the editor to display the string 0 in the end: 00B, 01B, 0B0, 1B0, BB0. In the last way, nothing will happen when the backspace key is pressed.
分析
用\(dp[i][j]\)來表示,進行了\(i\)次操作,當前字串長度為\(j\)的方法數.在dp[i][j]這個狀態下,我們有三種選擇
- 可以按1或0,\(dp[i+1][j+1]+=dp[i][j]\)
- 或者按退格,\(dp[i+1][max(0,j-1)]+=dp[i][j]\);
因為通過dp[i][j]前邊的來推導當前不好處理,可以在到達dp[i][j]之前就使用dp[i][j]的前驅更新完畢.
代碼
expand
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;typedef long long ll;const int maxn=5050;const ll MOD=1e9+7;const int inf=0x3f3f3f3f;char s[maxn];int dp[maxn][maxn];int inv[maxn];ll Pow(ll x,ll n){ ll ans=1,base=x; while(n){ if(n&1) ans=ans*base%MOD; base=base*base%MOD; n>>=1; } return ans;}int sum[2][maxn];int main(int argc, char const *argv[]){ inv[0]=1; inv[1]=Pow(2,MOD-2); for (int i = 2; i < maxn; ++i) { inv[i]=(ll)inv[i-1]*inv[1]%MOD; } int n,m; // scanf("%d%d", &n,&m); scanf("%d %s", &n,s+1); m=strlen(s+1); for (int i = 0; i <= n; ++i) { for (int j = 0; j<=i; ++j) { int &u=dp[i][j]; if(i==0&&j==0) u=1; else if(i==0) u=0; else if(i==1&&j==0) u=1; if(j) dp[i+1][j-1]=(dp[i+1][j-1]+u)%MOD; else dp[i+1][j]=(dp[i+1][j]+u)%MOD; dp[i+1][j+1]=(dp[i+1][j+1]+u*2%MOD)%MOD; } } printf("%lld\n", (ll)dp[n][m]*inv[m]%MOD); return 0;}
Unhappy Hacking II