题目
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 (109+7).
题意: 给出 n 和 m , n 代表 AB 的个数, m代表BA的个数 ,求字符串S(由n个AB和m个BA组成)有多少种
题解:
我们对这道题进行分析,有n个AB和m个BA,那么一定有前n个A是属于AB的,同样有前m个B是属于BA的。对于合法解中有重叠子问题,那么我们用动态规划的思路来考虑。
我们构建一个状态方程式 dp[i][j] 代表已选上 i 个 A 与 j 个 B。
状态转移分析:当 i<n 的时候,可以直接插入A,因为非A即B,要保证前n个B的前面至少有n个A。当 i>=n 的时候,A不能超过目前还需匹配成“BA”的B的最大数目,即多出的A不能超过min(j,m) ,表达式:当 i−n<min(j,m),还可以继续插入A。
同理B的判断也跟A相同。边界值:dp[0][0]=1,n=m=0有且仅有一个解。
原文来自:大佬题解
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD=1000000007;
int dp[2005][2005];
int main(){
int n, m;
while(cin >> n >> m){
for(int i = 0; i <= n+m; i++){
for(int j = 0; j <= n+m; 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 || (i-n) < min(j, m)){ // A 的数量小于n时,直接插入A
dp[i+1][j] += dp[i][j]; // A 的数量大于n时,保证A的数量小于此时B的数量
dp[i+1][j] %= MOD;
}
if(j < m || (j-m) < min(i, n)){ // 道理同 A
dp[i][j+1] += dp[i][j];
dp[i][j+1] %= MOD;
}
}
}
cout << dp[n+m][n+m] << endl;
}
return 0;
}