E题.ABBA
链接:https://ac.nowcoder.com/acm/contest/881/E
来源:牛客网
题目描述
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 ( 1 0 9 10^9 109+7)
输入描述:
The input consists of several test cases and is terminated by end-of-file.
Each test case contains two integers n and m.
* 0≤n,m≤
1
0
3
10^3
103
0≤n,m≤
1
0
3
10^3
103
* There are at most 2019 test cases, and at most 20 of them has
max{n,m}>50.
输出描述:
For each test case, print an integer which denotes the result.
示例1
输入
1 2
1000 1000
0 0
输出
13
436240410
1
题目大意:
有一个长度为2(n+m)的字符串,如果它能划分成(n+m)个长度为2的子序列,使得这些子序列有n个是AB,m个是BA,那么这个字符串就合法。给出n和m,问有多少种合法的字符串。
思路(DP):
首先,我们先来理解一下题目的意思。
题目说一个字符串只包含’A’,‘B’,可以分成n个"AB",和m个"BA"
然后我们看看样例1 2的全部13种可能结果:
ABABAB ABABBA
ABBAAB ABBABA
ABBBAA BAABBA
BAABAB BABAAB
BABABA BABBAA
BBAAAB BBAABA
BBABAA
因为一共要放n+m个A和B。A一定要有n个在B前面,B一定要m个在B前面,所以要分
如果i≤n,那么′A′可以随意放; 如果j≤m,那么′B′可以随意放;
当A超过n个时,这时候,再放A就得前面有B与它匹配。(因为“BA”)
当B超过m个时,这时候,再放B就得前面有A与它匹配。(因为“AB”)
所以总的状态转移方程:
dp[ i ][ j ] 表示放了i个′A′和j个′B′的方案数,然后考虑转移到下一个状态:
- 如果i≤n,那么′A′可以随意放;
- 如果j≤m,那么′B′可以随意放;
- 如果i>n,那么要放′A′需要放了′A′后多余的′A′前面要有′B′和它匹配,也就是说i-n≤j,否则只能放‘B’;
- 如果j>m,那么要放′B′需要放了′B′后多余的′B′前面有′A′和它匹配,也就是说j-m≤i,否则只能放’A’。
#include <bits/stdc++.h>
using namespace std;
const int N=2007;
const int mod=1e9+7;
int dp[N][N];
int main() {
int n,m;while(~scanf("%d%d",&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++){ //i个A
for (int j=0;j<=(n+m);j++){ //j个B
if(i<n+j){ //A的个数小于所有AB(n)加上已经出现的BA的B的个数(j)
dp[i+1][j]=dp[i][j]; // 本来为(dp[i+1][j]+dp[i][j])%mod;以往能到达dp[i+1][j]的加上这次的,但dp[i+1][j]为0,则可以省略。
}
if(j<m+i){ //B的个数小于所有BA(m)加上已经出现的AB的A的个数(i)
dp[i][j+1]=(dp[i][j+1]+dp[i][j])%mod; //以往能到达dp[i][j+1]的加上这次的
}
}
}
printf("%d\n",dp[n+m][n+m]);
}
return 0;
}