zoukankan      html  css  js  c++  java
  • Codeforces 629C Famil Door and Brackets

    题意:

    给定长度为m的序列s,求一共有多少对p,q,使得:

    • p+s+q长度为n,且’(‘数与’)’数相等。
    • p+s+q的任意前缀’(‘数比’)’数多。

    其中s,p,q均为’(‘和’)’组成的序列。

    分析:

    dp[i][j]为长度为i的序列中’(‘比’)’多的个数为j的情况数,很容易想到时间和空间复杂度均为O(n(nm))的方法。但是如果p+s中’(‘比’)’多的个数为j,那么q中’(‘比’)’多的个数为j即可,利用对称性,这样情况数又等于dp[i][j]。把j所有可能值都算出来,最后在将jj的情况数相乘即可。时间空间复杂度为O((nm)2)

    代码:

    #include<cstdio>
    #include<cstring>
    #include<iostream>
    using namespace std;
    const int INF=0x3fffffff, maxn = 1e5 + 5, maxm = 2005, mod = 1e9 + 7;
    char a[maxn];
    long long dp[maxm][maxm];
    int n, m;
    int main (void)
    {
        int n, m, cnt = 0;
        scanf("%d%d",&n, &m);
        scanf("%s", a);
        int lcnt = INF;
        for(int i = 0; i < m; i++){
            if(a[i] == '(') cnt++;
            else  cnt--;
            if(i == 0) lcnt = cnt;
            lcnt = min(lcnt, cnt);
        }
        long long res = 0;
        dp[0][0] = 1;
        for(int i = 1; i <= n - m; i++){
            for(int j = 0; j <= i; j++){
                if(j == 0) {
                    dp[i][j] = dp[i - 1][j + 1];
                    continue;
                }
                dp[i][j] =(dp[i - 1][j - 1] + dp[i - 1][j + 1]) % mod ;
            }
        }
        for(int i = 0; i <= n - m; i++){
            for(int j = 0; j <= i; j++){
                if(j + lcnt >= 0&&j + cnt <= n - m){
                     res += dp[i][j] * dp[n - m - i][j + cnt];
                     res %= mod;
                }
            }
        }
        printf("%I64d
    ", res);
        return 0;
    }
    
  • 相关阅读:
    [LeetCode] 582. Kill Process
    [LeetCode] 686. Repeated String Match
    [LeetCode] 341. Flatten Nested List Iterator
    [LeetCode] 404. Sum of Left Leaves
    [LeetCode] 366. Find Leaves of Binary Tree
    [LeetCode] 1485. Clone Binary Tree With Random Pointer
    [LeetCode] 459. Repeated Substring Pattern
    [LeetCode] 565. Array Nesting
    [LeetCode] 679. 24 Game
    [LeetCode] 364. Nested List Weight Sum II
  • 原文地址:https://www.cnblogs.com/Tuesdayzz/p/5758762.html
Copyright © 2011-2022 走看看