CSU 1271 Brackets Sequence

1271: Brackets Sequence

     Time Limit: 1 Sec     Memory Limit: 128 Mb     Submitted: 354     Solved: 175    

Description

Let us define a regular brackets sequence in the following way:

1. Empty sequence is a regular sequence.

2. If S is a regular sequence, then (S) is a regular sequence.

3. If A and B are regular sequences, then AB is a regular sequence.

For example, these sequences of characters are regular brackets sequences: (), (()), ()(), ()(()), ((())())().

And all the following character sequences are not: (, ), ((), ()), ())(, (()(, ()))().

A sequence of characters '(' and ')' is given. You can insert only one '(' or ')' into the left of the sequence, the right of the sequence, or the place between any two adjacent characters, to try changing this sequence to a regular brackets sequence.

Input

The first line has a integer T (1 <= T <= 200), means there are T test cases in total.

For each test case, there is a sequence of characters '(' and ')' in one line. The length of the sequence is in range [1, 105].

Output

For each test case, print how many places there are, into which you insert a '(' or ')', can change the sequence to a regular brackets sequence.

What's more, you can assume there has at least one such place.

Sample Input

4
)
())
(()(())
((())())(()

Sample Output

1
3
7
3

题意:每一个左括号都有相应的右括号与之对应的序列为regular sequence.否则不是,现在给你一个不规律的序列,你可以在这个序列的某个地方插入一个左括号或者右括号来使其规则;问有多少个这样的地方;

思路:括号配对,找出未配对的括号的位置,如果是左括号,看其前面的有多少的位置,右括号看后面的;

下面附上我的代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
char s[100005];
struct node{
	int x;
	char c;
}k[100005];
int main()
{
	int t;
	cin>>t;
	getchar();
	while(t--)
	{
		stack <node> p;
		gets(s);
		int l = strlen(s);
		for(int i=0;i<l;i++)
		{
			k[i].c=s[i];
			k[i].x=i;
		}
		p.push(k[0]); 
		int h=1;
		while(h<l)
		{
			if(p.empty() )
				p.push(k[h]);
			else if(k[h].c==')'&&p.top().c=='(')
				p.pop();
			else
				p.push(k[h]);
			h++;
		}
		if(p.empty())
			puts("0");
		else if(p.top().c=='(')
			printf("%d\n",l-p.top().x);
		else
			printf("%d\n",p.top().x+1);
	}
	return 0;




猜你喜欢

转载自blog.csdn.net/gtuif/article/details/79933783
今日推荐