牛客NOIP普及组R1 C括号(dp)

本文介绍了一种使用动态规划解决括号匹配问题的方法。通过定义状态$f[i][j]$来表示当前处理到第$i$个字符时剩余未匹配的左括号数为$j$的情况数量,利用这一定义进行状态转移,最终求解出所有可能的有效括号组合数量。

题意

题目链接

Sol

maya普及组的dp都要想很长时间,我真是越来越菜了qwq

设$f[i][j]$表示当前到第$i$个位置,剩下$j$个左括号没被匹配

转移的时候判断一下即可

/*
 
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<vector>
#include<set>
#include<queue>
#include<cmath>
#define Pair pair<int, int>
#define MP(x, y) make_pair(x, y)
#define fi first
#define se second
#include<set>
#include<vector>
//#define int long long
#define LL long long
//#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<22, stdin), p1 == p2) ? EOF : *p1++)
//char buf[(1 << 22)], *p1 = buf, *p2 = buf;
using namespace std;
const int MAXN = 1e5 + 10, INF = 1e9 + 10, mod = 1e9 + 7;
const double eps = 1e-9;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int N;
char s[MAXN];
int f[2][MAXN];
int main() {
//    freopen("a.in", "r", stdin);
//    freopen("c.out", "w", stdout);
    N = read();
    scanf("%s", s + 1);
    int o = 1; f[0][0] = 1; 
    for(int i = 1; i <= N; i++, o ^= 1) {
        //(f[i][j] += f[i - 1][j]) %= mod;
        memset(f[o], 0, sizeof(f[o]));
        if(s[i] == '(') {
            
            for(int j = 0; j <= i; j++) 
                (f[o][j] += f[o ^ 1][j]) %= mod, (f[o][j] += f[o ^ 1][j - 1]) %= mod;            
        }

        else {
            
            for(int j = 0; j <= i; j++)
                (f[o][j] += f[o ^ 1][j]) %= mod, (f[o][j] += f[o ^ 1][j + 1]) %= mod;            
        }

    }
    printf("%d", (f[o ^ 1][0] - 1 + mod) % mod);
    return 0;
}
/*
2
()

3
())


8
)(()(())
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值