51 nod 合法括号子段 (单调栈)
2017-08-14 10:24
281 查看
合法括号子段
System Message (命题人)
基准时间限制:1 秒 空间限制:131072 KB 分值: 40
有一个括号序列,现在要计算一下它有多少非空子段是合法括号序列。
合法括号序列的定义是:
1.空序列是合法括号序列。
2.如果S是合法括号序列,那么(S)是合法括号序列。
3.如果A和B都是合法括号序列,那么AB是合法括号序列。
Input
Output
Input示例
Output示例
同级之间加数累加加1,不同级之间值为1
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; }
相关文章推荐
- 【51nod 1791】 合法括号子段
- 51 Nod 1791 合法括号子段【分治+字符串】
- 【51Nod1791】合法括号子段
- 51 nod 1623 完美消除(单调栈+数位DP)
- 51 nod 1158 全是1的最大子矩阵(单调栈)
- 51Nod-1791-合法括号子段
- 51nod 1791 合法括号子段(DP)
- 51 Nod 1315 合法整数集
- 51NOD 1791 合法括号子段
- 合法括号子段 51Nod - 1791 **
- 51nod 1791 合法括号子段 (队列)
- 51 NOD 1315 合法整数集(思维 + 模拟)
- 合法括号子段
- 51 nod 1275 连续子段的差异(单调队列)
- 51 nod 1254 最大子段和 V2(思维)
- 51nod 1791 合法括号子段
- H 子段求和(51Nod 1081)
- 合法括号子段
- 51 nod 1255 字典序最小的子序列(单调栈 贪心)
- 51 NOD 1279 扔盘子(单调栈)