2019牛客多校第一场E ABBA(DP)题解

链接:https://ac.nowcoder.com/acm/contest/881/E
来源:牛客网

ABBA
时间限制: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
(
10
9

  • 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

    10
    3
    0≤n,m≤103
  • There are at most 2019 test cases, and at most 20 of them has
    max
    {
    n
    ,
    m
    }

    50
    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个‘A'和’B'组成,要求有n个AB子序列,和m个BA子序列,这样的串有多少种 ?
思路:

先看一个合法串什么什么样的,因为子序列有n个AB,m个BA,那么显然前n个A必为AB的A,前m个B必为BA的B,因为如果我前n个A中有一个是BA的A,那么我们可以从更后面 随便找一个A给这个B用。

定义dp状态: dp[i][j] 为放了i个A,j个B,合法的状态数。

来看转移:

放A:
如果i < n 那么可以直接放这个A,理由如上。

如果i>=n 那么我们要确保 这个放的A能给前面的B当作BA中的A用,那么当前我们BA需要的A是min(j,m) 个

已经给了i-n个,故如果(i-n)

B 同理:
如果j< m 直接放这个B

如果j > = m ,那么我们要确保 放这个B能给前面的一个A当作AB中的B用,那么我们AB需要的B是 min(i,n )个

已经放了 j-m 个,如果(j-m) 

细节见代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define ALL(x) (x).begin(), (x).end()
#define rt return
#define dll(x) scanf("%I64d",&x)
#define xll(x) printf("%I64d\n",x)
#define sz(a) int(a.size())
#define all(a) a.begin(), a.end()
#define rep(i,x,n) for(int i=x;i
#define pll pair
#define gbtb ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define MS0(X) memset((X), 0, sizeof((X)))
#define MSC0(X) memset((X), '\0', sizeof((X)))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define eps 1e-6
#define gg(x) getInt(&x)
#define chu(x) cout<<"["<<#x<<" "<<(x)<<"]"<> n >> m) {
        repd(i, 0, n + m) {
            repd(j, 0, n + m) {
                dp[i][j] = 0;
            }
        }
        dp[0][0] = 1;
        repd(i, 0, n + m) {
            repd(j, 0, m + n) {
                if (i < n || i - n < j) {
                    dp[i + 1][j] += dp[i][j];
                    dp[i + 1][j] %= mod;
                }
                if (j < m || (j - m) < i) {
                    dp[i][j + 1] += dp[i][j];
                    dp[i][j + 1] %= mod;

                }
            }
        }
        cout<= '0' && ch <= '9') {
            *p = *p * 10 - ch + '0';
        }
    } else {
        *p = ch - '0';
        while ((ch = getchar()) >= '0' && ch <= '9') {
            *p = *p * 10 + ch - '0';
        }
    }
}



转载于:https://www.cnblogs.com/qieqiemin/p/11210411.html

你可能感兴趣的:(数据结构与算法,c/c++)