The Monster
题目传送门
题意:给你一个字符串,这个字符串由’(”)”?’组成,?可以转化为(、)。问该字符串的所有子串中有多少个子串中括号全部匹配。
思路:数据大小为5000,因此可以在1s内枚举所以子串,所以要考虑如何判断子串是否符合条件。
先不考虑?,我们可以想到一个模拟操作Satck,第一个字符一定为(,随后遇到(就入栈,遇到)就出栈,当需要出栈时如果栈空,那么这子串则不可能符合条件,符合条件时栈空。
考虑?时,?有两种情况,所以我可以假定一种情况,例如令它为),如果随后不符合要求则,令它为(.
因为入栈的只有(,所以完全可以用一个变量代替,并且在枚举子串的同时判断是否符合要求。
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <cmath>
#include <algorithm>
#include <functional>
#define inf 10000000
using namespace std ;
typedef long long ll;
const int MAXN=5e6 +10 ;
const int MAX=1e6 +10 ;
const double eps=1e-6 ;
string s;
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("in.txt" ,"r" ,stdin);
#endif
cin >>s;
int ans=0 ;
for (int i=0 ;i<s.size();i++){
int temp=0 ,cnt=0 ;
for (int j=i;j<s.size();j++){
if (s[j]=='(' )
temp++;
if (s[j]==')' )
temp--;
if (s[j]=='?' )
temp--,cnt++;
if (temp<0 ){
if (cnt)
temp+=2 ,cnt--;
else
break ;
}
if (!temp)
ans++;
}
}
cout <<ans<<endl;
return 0 ;
}