Problem A : Corn's new language
Description
Corn is going to promote programming in the campus, so he wants to add a lot of interesting ideas to make programming more attractive. One task he is working on is to develop a new programming language because he thinks all existing ones are too simple to him. The syntax rules of the language are:
1. () () is a valid program
2. (P) (P) is a valid program, if P P is a valid program
3. PQ PQ is a valid program, if both P P and Q Q are valid programs
Corn wants a compiler for the language. For a program, if it is valid, the compiler should print the max depth in the program. For example " (()) (())" has a depth of 2 2, while " ((())()) ((())())" has a depth of 3 3. Formally, the max depth is the max number of unmatched open brackets in any prefix.
Input
Each case is a non-empty string in a single line, the string will only contain ' ( (' or ' ) )', its length will be no more than 100 100.
Output
For each case, output "YES" and the integer required above if the program is valid, separated with a space. Or "NO" if the program is invalid.
Sample Input
( ) () (()) ((())()) ()) ((
Sample Output
NO NO YES 1 YES 2 YES 3 NO NO
分析
这道题是在括号匹配的基础上加上了一个深度的记录,这个深度记录就可以简单地定义一个变量初始为0记录深度,再定义一个变量记录最大深度,然后从头到尾来判断这个字符串中括号的方向,如果为‘(’则该变量++,如果为‘)’则该变量--,每次改变后与最大深度比较。
代码
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
int main()
{
char str[110];
while(scanf("%s",str)!=EOF)
{
int maxn=0,num=0;//maxn存放最大深度
for(int i=0;i<strlen(str);i++)
{
if(str[i]=='(')num++;
if(str[i]==')')num--;
maxn=max(maxn,num);//将各个位置的深度与最大深度对比,然后存放大的那个值
}
stack<char>s;
int len=strlen(str);
for(int i=0;i<len;i++)
{
if(s.empty())
{
s.push(str[i]);
}
else
{
if(s.top()+1==str[i]||s.top()+2==str[i])//判断栈内元素是否与下一个即将入栈的元素匹配
{
s.pop();//如果匹配将栈顶元素出栈
}
else
{
s.push(str[i]);//如果不匹配,则下一个元素入栈
}
}
}
if(s.empty())//如果栈为空,说明括号都已经匹配
{
printf("YES %d\n",maxn);
}
else
{
printf("NO\n");
}
}
return 0;
}