合法括号子段 51Nod - 1791

本文介绍了一种使用栈和动态规划解决括号匹配问题的方法。通过栈找出每个右括号能向左匹配多远,然后计算独立及两两拼接的合法序列数量。代码示例展示了如何初始化和求解问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.51nod.com/Challenge/Problem.html#!#problemId=1791

先用栈找出每个右括号向左能匹配多远 这样是找出了所有独立的合法序列 然后再算上两两拼接而成的新合法序列 dp数组维护一下就好

 

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=2e6+10;

stack <int> stk;
ll dp[maxn];
int pos[maxn];
int n;
char ch[maxn];

void init()
{
    int i,p;
    while(!stk.empty()) stk.pop();
    for(i=1;i<=n;i++) pos[i]=-1;
    for(i=1;i<=n;i++){
        if(ch[i]=='(') stk.push(i);
        else{
            if(!stk.empty()){
                p=stk.top();
                stk.pop();
                pos[i]=p-1;
            }
        }
    }
}

ll solve()
{
    ll res;
    int i;
    for(i=1;i<=n;i++) dp[i]=0;
    res=0;
    for(i=1;i<=n;i++){
        if(pos[i]!=-1) dp[i]=dp[pos[i]]+1;
        res+=dp[i];
    }
    return res;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%s",ch+1);
        n=strlen(ch+1);
        init();
        printf("%lld\n",solve());
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值