您的位置:首页 > 其它

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

2017-08-14 10:24 281 查看
合法括号子段 




 

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
;
struct node
{
int x, id;
};
stack<node>st;
LL a
;

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: