51nod 1791 合法括号子段(模拟)

基准时间限制: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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值