51nod 1791 合法括号子段(模拟)
2017-09-11 22:28
309 查看
1791 合法括号子段
基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
收藏
关注
有一个括号序列,现在要计算一下它有多少非空子段是合法括号序列。
合法括号序列的定义是:
1.空序列是合法括号序列。
2.如果S是合法括号序列,那么(S)是合法括号序列。
3.如果A和B都是合法括号序列,那么AB是合法括号序列。
Input
Output
Input示例
Output示例
System Message (题目提供者)
Visual C++的运行时限为:1000 ms ,空间限制为:131072 KB 示例及语言说明请按这里
允许其他 AC 的用户查看此代码,分享代码才能查看别人的代码并有机会获得勋章
本来以为是DP,但是想了想根本就不用dp,直接栈模拟括号配对的过程,
然后定义个pos数组记录能和之前的合法括号组合构成合法括号的方案数就好啦。
基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
收藏
关注
有一个括号序列,现在要计算一下它有多少非空子段是合法括号序列。
合法括号序列的定义是:
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
System Message (题目提供者)
Visual C++的运行时限为:1000 ms ,空间限制为:131072 KB 示例及语言说明请按这里
允许其他 AC 的用户查看此代码,分享代码才能查看别人的代码并有机会获得勋章
本来以为是DP,但是想了想根本就不用dp,直接栈模拟括号配对的过程,
然后定义个pos数组记录能和之前的合法括号组合构成合法括号的方案数就好啦。
#include<set> #include<map> #include<stack> #include<queue> #include<vector> #include<string> #include<math.h> #include<time.h> #include<stdio.h> #include<iostream> #include<string.h> #include<stdlib.h> #include<algorithm> #include<functional> using namespace std; typedef long long ll; #define inf 1000000000 #define mod 1000000000 #define maxn 1100005 #define PI 3.1415926 #define lowbit(x) (x&-x) #define eps 1e-9 char ss[maxn]; struct node { char s; int x; }; stack<node>s; ll pos[maxn]; int main(void) { ll T, i, num, ans, p1, p2; scanf("%lld", &T); while (T--) { ans = 0; while (s.empty() == 0) s.pop(); scanf("%s", ss + 1); int len = strlen(ss + 1); for (i = 0;i <= len;i++) pos[i] = 0; for (i = 1;i <= len;i++) { if (ss[i] == ')') { if (s.empty() == 0) { ans++; node str; str = s.top(); if (ss[str.x - 1] == ')') pos[i] = pos[str.x - 1] + 1; else pos[i] = 1; ans += pos[str.x - 1]; s.pop(); } } else { node str; str.s = ss[i]; str.x = i; s.push(str); } } printf("%lld\n", ans); } return 0; }
相关文章推荐
- 合法括号子段 51Nod - 1791 **
- 51nod 1791 合法括号子段 (dp)
- 51nod 1791 合法括号子段(DP)
- 51Nod 1791 合法括号子段(栈+乱搞)
- 51nod 1791 合法括号子段
- 51NOD 1791 合法括号子段
- 合法括号子段 51Nod - 1791 (栈+dp)
- 51nod 1791 合法括号子段
- 51nod 1791 合法括号子段 (队列)
- 51Nod-1791-合法括号子段
- 51nod 1791 合法括号子段 DP
- 51nod-1791-合法括号子段
- 51 Nod 1791 合法括号子段【分治+字符串】
- 51nod 合法括号子段
- 【51nod 1791】 合法括号子段
- 51nod_1791——合法括号字段
- 1791 合法括号子段
- 51nod 1478-括号序列的最长合法子段(模拟)
- 【51Nod1791】合法括号子段
- [分治] 51nod算法马拉松27 A.合法括号子段