51nod1791 合法括号子段

本文提供了一种解决1791合法括号子段问题的算法实现,通过使用栈来记录左括号及有效的括号配对情况,并计算所有合法括号子段的数量。

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

1791 合法括号子段

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define ll long long
const int MOD = 1E9+7;
const int N = 1000000+5;
const int dx[] = {0,0,-1,1,-1,-1,1,1};
const int dy[] = {-1,1,0,0,-1,1,-1,1};
using namespace std;

char s[1100005];
stack<char>st;
int main(){
    int t;
    ll cnt;
    ll ans;
    scanf("%d",&t);
    while(t--){
            ll ans=0;
            while(st.size()){
                st.pop();
            }
        scanf(" %s",s);
        int l=strlen(s);
        for(int i=0;i<l;i++){
             if(s[i]=='('){
                    st.push(s[i]);
                }
                else if(s[i]==')'){
                    if(st.size()==0){
                        st.push(s[i]);
                    }
                    else if(st.top()=='('){
                                st.pop();
                                st.push('|');
                    }
                    else if(st.top()=='|'){
                        cnt=0;
                        while(st.size()){
                            if(st.top()=='|'){
                                cnt++;
                                st.pop();
                            }
                            else break;
                        }
                        ans+=(cnt+1)*cnt/2;
                        if(st.size()){
                            if(st.top()=='('){
                                st.pop();
                                st.push('|');
                               }
                               else st.push(s[i]);
                        }
                        else st.push(s[i]);
                    }
                    else st.push(s[i]);
                }
        }
        cnt=0;
        while(st.size()){
            if(st.top()=='|'){
                while(st.size()){
                    if(st.top()=='|'){
                        cnt++;
                        st.pop();
                    }
                    else break;
                }
                ans+=(cnt+1)*cnt/2;
            }
            else {
                cnt=0;
                st.pop();
            }
        }
        printf("%lld\n",ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值