ABBA 2019牛客暑期多校训练营(第一场)

题目链接: 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 1e9+7

大意: 问你一个字符串刚好拆成n个AB ,m个BA的子序列的方案数有多少
思路: 首先对于空字符串要么先放A要么先放B,对于先放A,每一个满足条件的字符串都必然满足前n个A与B匹配,后m个A与B匹配的这种分配情况。对于先放B与此类似
所以dp[ i ][ j ]表示有i个A,j个B的合法方案数,若我们先放A,若j>i-n,也就是说下一步我们要放A构成BA,反之先考虑放B

#include
using namespace std;
const int mod=1e9+7;
typedef long long ll;
ll dp[2005][2005];
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++)
		{
			for(int j=0;j<=n+m;j++)
			{
				if(j>i-n)
				{
					dp[i+1][j]=(dp[i+1][j]+dp[i][j])%mod;
				}
				if(i>j-m)
				{
					dp[i][j+1]=(dp[i][j+1]+dp[i][j])%mod;
				}
			}
		}
		printf("%lld\n",dp[n+m][n+m]);
	}
	return 0;
}

你可能感兴趣的:(思维,DP)