【ACWing】889. 满足条件的01序列

题目地址:

https://www.acwing.com/problem/content/891/

给定 n n n 0 0 0 n n n 1 1 1,构造一个长 2 n 2n 2n的序列,要求对于任意前缀, 1 1 1的个数都大于等于 0 0 0的个数。答案模 1 0 9 + 7 10^9+7 109+7输出。

数据范围:
1 ≤ n ≤ 1 0 5 1\le n\le 10^5 1n105

答案是Catalan数。参考https://blog.csdn.net/qq_46105170/article/details/104243540。有公式: C n = 1 n + 1 ( 2 n n ) C_n=\frac{1}{n+1}{2n \choose n} Cn=n+11(n2n)这里还需要用到快速幂求逆元,参考https://blog.csdn.net/qq_46105170/article/details/113823892。代码如下:

#include <iostream>
using namespace std;

const int mod = 1e9 + 7;

int fast_pow(int a, int k, int p) {
    
    
    int res = 1;
    while (k) {
    
    
        if (k & 1) res = (long) res * a % p;
        a = (long) a * a % p;
        k >>= 1;
    }

    return res;
}

int main() {
    
    
    int n;
    cin >> n;

    int a = 2 * n, b = n;
    int res = 1;

    for (int i = a; i > a - b; i--) res = (long) res * i % mod;
    for (int i = 1; i <= b; i++) res = (long) res * fast_pow(i, mod - 2, mod) % mod;

    res = (long) res * fast_pow(n + 1, mod - 2, mod) % mod;
    
    cout << res << endl;

    return 0;
}

时间复杂度 O ( n log ⁡ p ) O(n\log p) O(nlogp) p = 1 0 9 + 7 p=10^9+7 p=109+7,空间 O ( 1 ) O(1) O(1)

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/114006509