棧——括號匹配

Scaena Felix

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 492    Accepted Submission(s): 214


Problem Description

Given a parentheses sequence consist of '(' and ')', a modify can filp a parentheses, changing '(' to ')' or ')' to '('.

If we want every not empty <b>substring</b> of this parentheses sequence not to be "paren-matching", how many times at least to modify this parentheses sequence?

For example, "()","(())","()()" are "paren-matching" strings, but "((", ")(", "((()" are not.

 


Input

The first line of the input is a integer T, meaning that there are T test cases.

Every test cases contains a parentheses sequence S only consists of '(' and ')'.

1|S|1,000.

 


Output

For every test case output the least number of modification.

 


Sample Input

3
()
((((
(())

 


Sample Output

1
0
2

題目最終就是要要求統計的匹配括號對,實際就是棧的應用。

源碼:


#include<iostream>

#include<cstdio>

#include<cstdlib>

#include<string>

#include<stack>

#include<vector>


using namespace std;


#define MAX 1009


template <class Type>


class Stack {

public:

Stack(int MaxStackSize = MAX);

bool IsFull();

bool IsEmpty();

void Push(const Type x);

Type Pop();

private:

int top;

Type *stack;

int MaxSize;

};


template<class Type>

Stack<Type>::Stack(int MaxStackSize) :MaxSize(MaxStackSize)

{

stack = new Type[MaxSize];

top = -1;

}


template<class Type>

inline bool Stack<Type>::IsFull()

{

if (top == MaxSize - 1)

return true;

else

return false;

}


template<class Type>

inline bool Stack<Type>::IsEmpty()

{

if (top == -1)

return true;

else

return false;

}


template<class Type>


void Stack<Type>::Push(const Type x)

{

if (IsFull())

;

else

stack[++top] = x;

}


template<class Type>


Type Stack<Type>::Pop()

{

if (IsEmpty())

{

return 0;

}

else

{

Type x = stack[top--];

return x;

}

return 0;

}


template<class Type>

int GetNum(const Type *S,int n)

{

int count = 0;

Type x = ' ';

Stack<Type> ST;

ST.Push(*S++);

for (int i = 1; i < n; i++)

{

x = ' ';

if (!ST.IsEmpty())

{

x = ST.Pop();

}

if (x == '('&&*S == ')')

{

count++;

*S++;

}

else

{

if (x!=' ')

ST.Push(x);

ST.Push(*S++);

}

}

return count;

}


int main()

{

int T = 0;

string S;

while (cin >> T) {

for (int i = T; i >= 1; i--)

{

cin >> S;

cout << GetNum(S.c_str(),S.size()) << endl;

}

}

return 0;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章