跳到正文

题解

题解 P1641 【[SCOI2010]生成字符串】

xyz32768约 4 分钟
原文
文章信息与版本

文章信息

发布
2017年8月27日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 4 分钟
获赞
109
题目
P1641

版本

  1. v1当前

可以考虑把11的个数与00的个数的和看成xx坐标,11的个数与00的个数的差看成yy坐标,那么如下图:

这里写图片描述

向右上走(xx坐标加11,yy坐标加11)就表示这个字符选择11。

向右下走(xx坐标加11,yy坐标减11)就表示这个字符选择00。

这样子,如果不考虑限制条件,就表示从(0,0)(0,0)走n+mn+m步到达(n+m,n−m)(n+m,n-m),这相当于从n+mn+m步中选出mm步向右下走,也就是C(n+m,m)C(n+m,m)。

考虑限制条件,任意前缀中11的个数不少于00的个数,也就是这条路径不能经过直线y=−1y=-1。可以通过对称性发现,从(0,0)(0,0)走到直线y=−1y=-1上的一点,相当于从(0,−2)(0,-2)走到该点。也就是说,路径经过直线y=−1y=-1的方案数就是从(0,−2)(0,-2)走n+mn+m步到达(n+m,n−m)(n+m,n-m),这个方案数可以用组合数表示为C(n+m,m−1)C(n+m,m-1)。

所以最后结果为C(n+m,m)−C(n+m,m−1)C(n+m,m)-C(n+m,m-1)。对于组合数,可以预处理阶乘后用乘法逆元计算。

代码:

C++
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read() {
    int res = 0; bool bo = 0; char c;
    while (((c = getchar()) < '0' || c > '9') && c != '-');
    if (c == '-') bo = 1; else res = c - 48;
    while ((c = getchar()) >= '0' && c <= '9')
        res = (res << 3) + (res << 1) + (c - 48);
    return bo ? ~res + 1 : res;
}
const int N = 2e6 + 5, PYZ = 20100403;
int n, m, fac[N], inv[N];
int qpow(int a, int b) {
    int res = 1;
    while (b) {
        if (b & 1) res = 1ll * res * a % PYZ;
        a = 1ll * a * a % PYZ;
        b >>= 1;
    }
    return res;
}
int C(int x, int y) {
    int z = 1ll * fac[x] * inv[y] % PYZ;
    return 1ll * z * inv[x - y] % PYZ;
}
int main() {
    int i; fac[0] = 1; n = read(); m = read();
    for (i = 1; i <= n + m; i++) fac[i] = 1ll * fac[i - 1] * i % PYZ;
    inv[n + m] = qpow(fac[n + m], PYZ - 2);
    for (i = n + m - 1; i >= 0; i--)
        inv[i] = 1ll * inv[i + 1] * (i + 1) % PYZ;
    printf("%d\n", (C(n + m, m) - C(n + m, m - 1) + PYZ) % PYZ);
    return 0;
}
原文
存档评论38 条抓取于