51 nod 合法括号子段 (单调栈)

 
System Message  (命题人)
基准时间限制:1 秒 空间限制:131072 KB 分值: 40

有一个括号序列,现在要计算一下它有多少非空子段是合法括号序列。

合法括号序列的定义是:

1.空序列是合法括号序列。

2.如果S是合法括号序列,那么(S)是合法括号序列。
3.如果A和B都是合法括号序列,那么AB是合法括号序列。


Input
多组测试数据。
第一行有一个整数T(1<=T<=1100000),表示测试数据的数量。
接下来T行,每一行都有一个括号序列,是一个由'('和')'组成的非空串。
所有输入的括号序列的总长度不超过1100000。
Output
输出T行,每一行对应一个测试数据的答案。
Input示例
5
(
()
()()
(()
(())
Output示例
0
1
3
1
2


同级之间加数累加加1,不同级之间值为1


#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
#include<map>
#include <bits/stdc++.h>
using namespace std;
const int N = 1100000+10;
typedef long long LL;
const LL mod = 1e9+7;
char str[N];
struct node
{
    int x, id;
};
stack<node>st;
LL a[N];

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        while(!st.empty())st.pop();
        scanf("%s",str);
        int len=strlen(str);
        LL ans=0;
        int l=0;
        for(int i=0; str[i]; i++)
        {
            if(str[i]==')')
            {
                l--;
                if(l<0)
                {
                    l=0;
                    while(!st.empty())
                    {
                        ans+=st.top().x;
                        st.pop();
                    }
                    continue;
                }

                while(!st.empty()&&st.top().id>l) ans+=st.top().x,st.pop();
                if(!st.empty()&&st.top().id==l)st.push((node)
                {
                    st.top().x+1,l
                });
                else st.push((node)
                {
                    1,l
                });
            }
            else l++;
        }
        while(!st.empty())
        {
            ans+=st.top().x;
            st.pop();
        }
        printf("%lld\n",ans);
    }
    return 0;
}



























  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值