Hrdyo OJ 1007 括号序列

· · 个人记录

给一个由左右括号构成的字符串 s,对于每一个位置 i,输出有多少个子串,满足这个子串是一个合法的括号序列,并且 i 这个位置在子串中。

就是此题其实30分暴力O(n^2)好做

#include<iostream>
#include<cstdio>
#include<stack>
#include<cstring> 
#define int long long
using namespace std;
const int maxn=1e7+5,mod=1e9+7;
stack<char> st;
char s[maxn];
int l,pre[maxn],ans; 
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin>>s;l=strlen(s);
    for(int i=l;i>=1;--i) s[i]=s[i-1];
    for(int i=1;i<=l;++i){
        while(!st.empty()) st.pop();
        for(int j=i;j<=l;++j){
            if(st.empty()) st.push(s[j]);
            else{
                if(s[j]==')'){
                    if(st.top()=='('){
                        st.pop();
                        if(st.empty()) pre[i]++,pre[j+1]--;
                    } 
                    else st.push(s[j]);
                }
                else st.push(s[j]);
            } 
        } 
    }
    for(int i=1;i<=l;++i) pre[i]+=pre[i-1];
    for(int i=1;i<=l;++i) ans=ans+i*pre[i]%mod;
    printf("%lld",ans); 
    return 0;
}

优化算法大抵是这样子 将同级的括号放在一起 将左边的统计下来 右边同级的统计下来 然后左边与右边相乘 就是区间的总贡献

然后你在去区间内部查询内部的东西就好

#include<iostream>
#include<cstdio> 
#include<cstring>
#include<stack>
#define int long long
using namespace std;
const int maxn=1e7+5,mod=1e9+7;
char ch[maxn];
int l,pre[maxn],top=-1,bac[maxn],ans,tot;
int st[maxn];
signed main() {
    scanf("%s",ch+1);l=strlen(ch+1);
    for(int i=1;i<=l;++i){
        if(ch[i]=='('){
            if(ch[i-1]==')') pre[i]=pre[i-1]+1;
            else pre[i]=1;
            st[++top]=i;
        }
        else{
            if(top>=0) pre[i]=pre[st[top]],top--;//你的右括号要与左括号相同  你要是匹配不上的话 就是0 
        }
    } 
    top=-1;
    for(int i=l;i>0;--i){
        if(ch[i]==')'){
            if(ch[i+1]=='(') bac[i]=bac[i+1]+1;
            else bac[i]=1;
            st[++top]=i;
        }
        else{
            if(top>=0) bac[i]=bac[st[top]],top--;//你的右括号要与左括号相同  你要是匹配不上的话 就是0 
        }
    }
    for(int i=1;i<=l;++i){
        if(ch[i]=='(') ans=(ans+pre[i]*bac[i]%mod)%mod;
        tot=tot+ans*i%mod;
        if(ch[i]==')') ans=((ans-pre[i]*bac[i]%mod)%mod+mod)%mod;
    }
    printf("%lld",tot);
    return 0;
}