链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网
时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 524288K,其他语言1048576K
64bit IO Format: %lld
题目描述
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)(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≤1030≤n,m≤103 * There are at most 2019 test cases, and at most 20 of them has max{n,m}>50max{n,m}>50.
输出描述:
For each test case, print an integer which denotes the result.
示例1
输入
1 2
1000 1000
0 0
输出
13
436240410
1
题意
Bobo的字符串长度为2(n + m),由字符'A'和'B'组成。这个字符串可以被分解成(n + m)个长度为2的子序列,在这(n + m)个子序列中,n个是' AB ',其他m个是' BA '。题中 , n 为' AB' 的个数, m为'BA'的个数 ,求字符串S有多少种
题解
由题意可得,每个字符串的前n个A一定是属于'AB'的A,前m个B一定是属于'BA'的B
遍历一遍,A的归属为:若AB无A,则A分配给AB;否则,分配给无A的BA(如果此时的BA已经有A,则不能放)
dp[i][j]:放了i个A和j个B后满足条件的方案数
可放A的条件(1||2):dp[i+1][j] += dp[i][j]
1.已放A的个数小于n(i<n)
2.已放A的个数大于等于n,并且剩余A的数量要小于要放的B的数量(n-i<j)
可放B的条件(1||2):dp[i][j+1] = dp[i][j+1] + dp[i][j]
1.已放B的个数小于m(j<m)
2.已放B的个数大于等于m,并且剩余B的数量要小于要放的A的数量(j-m <i)
AC代码
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cctype>
#include<cmath>
#include<queue>
#include<stack>
#include<set>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;
const int mod=1000000007;
const int maxn=2e4;
int dp[maxn][maxn];
int n, m,i,j;
int main(){
while(cin >> n >> m){
for(i = 0; i <= n+m; i++){
for(j = 0; j <= n+m; j++){
dp[i][j] = 0;
}
}
dp[0][0] = 1;
for(i = 0; i <= n+m; i++){
for(j = 0; j <= n+m; j++){
if(i < n || i-n < j)
dp[i+1][j] = (dp[i+1][j] + dp[i][j]) % mod;
if(j < m || j-m <i)
dp[i][j+1] = (dp[i][j+1] + dp[i][j]) % mod;
}
}
cout << dp[n+m][n+m] << endl;
}
return 0;
}