题目描述:
Bobo has a string of length 2(n + m) which consists of characters A
and B
. The string also has a fascinating property: it can be decomposed into (n + m) subsequences of length 2, and among the (n + m) subsequences n of them are AB
while other m of them are BA
.
Given n and m, find the number of possible strings modulo 1e9 + 7
(n,m <= 1000)
题意:
求有多少种长度为2*(n+m)的字符串使得可以凑出n个‘AB’ 和 m个’BA’,比如当n = 1, m = 1的时候,有ABAB,BAAB,BABA,ABBA四种满足的字符串,答案对1e9+7取模。
题解:
思考这样一个问题:给你一个长为2*(n+m)的字符串,判断它是否能分解出n个’AB’和m个’BA‘。
贪心的思想,我们从前往后扫一遍,遇到A,如果还有’AB’没分到’A’,就把这个’A’分给’AB‘,否则看看’BA’中是否有分到了’B’但还没有分到’A’的,如果有,就把这个’A’分给他,如果没有,那么这个’A’就无法和任何东西配,这个字符串就不满足条件。
有了分配’A’和’B’的原则之后,我们就可以开始dp了。dp[i][j]表示放了i个’A’,j个’B’后依然有可能满足条件的方案数。
dp[i][j]的转移:
考虑放‘A’:
如果当前已经放的‘A’的个数比需要的’AB’个数少,可以直接放
如果当前已经放的’A’的个数大于等于n了,看看放了多少个‘B’,如果放的’B‘的个数小于多出来的’A’,可以直接放。
所以 dp[i+1][j] += dp[i][j] (i < n + j)
'B’同理。
这题的关键是要先想好怎么去分配A和B的归属,然后再去想dp。
ac代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 2e3 + 50;
const ll mod = 1e9 + 7;
ll dp[maxn][maxn];
int n, m;
int main()
{
while(~scanf("%d%d", &n, &m)){
for(int i = 0; i <= n + m; ++i){
for(int j = 0; j <= m + n; ++j) dp[i][j] = 0;
}
dp[0][0] = 1;
for(int i = 0; i <= n + m; ++i){
for(int j = 0; j <= n + m; ++j){
if(i < n + j) dp[i+1][j] = (dp[i+1][j] + dp[i][j]) % mod;
if(j < m + i) dp[i][j+1] = (dp[i][j+1] + dp[i][j]) % mod;
}
}
printf("%lld\n", dp[n+m][n+m]);
}
}