C. The Monster bracket matching

The main idea of ​​The Monster
title:
Given a string containing only ( ? ) three symbols, find out how many substrings are perfectly matched.
For example

( ) ? )  =>  ( ) ( ) 完美匹配
( ( ) ? => ( ( ) )完美匹配
? ? ? ? => ( ) ( )
     => ( ( ) )
     算一种子串

length<5000 , 1000ms
analysis:
This length and time limit are quite strange, I can't think of a better way, I guess it should be a little optimization based on n2. The result is indeed like this
Enumerate two endpoints have not tried, may be Timeout The starting point of the
enumeration starts to traverse backward and mark

if  ( 
    cnt++
else if  ) 
    cnt--
else 
    f++
    cnt++

First put ? when (count
if ) there are too many break
if ? can take the value to make this substring true, answer ++;
this is done

There
is key step missing... If it is only calculated according to such a small relationship, there will be errors
. The reason is that every time you get the final result of the current position, you don't know the order so that the processing of ? ( and ( ? The same will make the answer +1
but the sequence cannot be obtained, how to avoid it? ( The situation is
easy to think of? ( The middle? It cannot be an unknown quantity but is definite (
before the judgment is made, what can be determined? All Determined, the rest are all variable?, and then judge whether it can be changed according to the requirements of the subject.

Implementation:

#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define inf 0x3f3f3f3f
#define mem(s,t) memset(s,t,sizeof s)
typedef pair<int,int> pii;
typedef long long ll;
const int MAXN =1e5+10;
int main() {
    string s;
    cin>>s;
    int cnt=0,f=0,ans=0;
    for(int i=0;i<s.size();i++){
        cnt=0,f=0;
        for(int j=i;j<s.size();j++){
            if(s[j]=='('){
                cnt++;
            }
            else if(s[j]==')'){
                cnt--;
            }
            else {
                f++;
                cnt++;
            }
            if(cnt<0) break;
            f=min(f,cnt/2);//最多需要 cnt/2个 的 ?来参与变化 其他的?都是可确定量
            if(cnt%2==0 && cnt/2<=f) ans++;//长度为偶数  && 可以取到 cnt/2的值
        }
    }
    cout<<ans<<endl;
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325407811&siteId=291194637