Codeforces 1294E Natasha, Sasha and the Prefix Sums 卡特兰数

Natasha, Sasha and the Prefix Sums

我们考虑每种方案的贡献放到最靠右的最大前缀上, 我们枚举最大的位置和最大的值,

发现左边和右边的方案数都可以用卡特兰数表示。

#include<bits/stdc++.h>
using namespace std;

const int N = 4007;
const int mod = 998244853;

int n, m;
int c[N][N];

inline int calc(int n, int m) {
    if(n == -1 && m == 0) return 1;
    if(n < 0 || m < 0) return 0;
    int ans = c[n + m][n];
    if(m) ans -= c[n + m][m - 1];
    if(ans < 0) ans += mod;
    return ans;
}

int main() {
    for(int i = 0; i < N; i++) {
        for(int j = c[i][0] = 1; j <= i; j++) {
            c[i][j] = c[i - 1][j] + c[i - 1][j - 1];
            if(c[i][j] >= mod) c[i][j] -= mod;
        }
    }
    int ans = 0;
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= n + m; i++) {
        for(int j = 1; j <= n; j++) {
            if(i + j & 1) continue;
            int x = (i + j) / 2;
            int y = i - x;
            if(x < 0 || y < 0 || x > n || y > m) continue;
            int ret = calc(x, y);
            x = n - x;
            y = m - y;
            if(y < x) continue;
            ret = 1LL * ret * calc(y - 1, x) % mod;
            ret = 1LL * ret * j % mod;
            ans += ret;
            if(ans >= mod) ans -= mod;
        }
    }
    printf("%d\n", ans);
    return 0;
}

/*
*/

猜你喜欢

转载自www.cnblogs.com/CJLHY/p/11788971.html
今日推荐