题解:P14882 [ICPC 2019 Yokohama R] Parentheses Editor

· · 题解

P14882 [ICPC 2019 Yokohama R] Parentheses Editor

part0 前言

这篇代码码风可能不太良好,但注释和变量名仍有可读性,欢迎提出建议!

part1 括号匹配

一个很经典的问题,考虑用栈维护。\ 每次将新括号入栈,如果原来的栈顶和当前括号能组成合法括号对,则将这一对括号弹出,视为匹配成功。\ 对于本题,由于要支持删除操作,可以再开一个栈存储已经匹配的括号对以及每个括号对应的入队时间戳(即下标),平均时间复杂度为 O\texttt(|S|\texttt)。

part2 维护答案

不难发现,一个平衡字符串可以划分成若干个括号对,且不存在包含关系,这启示我们可以维护一个数组 pre,表示在第 i 个括号前有多少个连续且相邻的括号对,注意形如 ()()(() 的字符串不是平衡字符串,因为中间插入了无关字符。\ 考虑将一个平衡字符串的贡献统计到最后一对括号上,则每一对括号的贡献为 pre_{pos_\texttt(},其中 pos_\texttt( 表示左括号的下标。\ 则每次匹配到新的括号对就更新答案,删除括号对时同理。由于 pre 数组的维护是线性的,故总时间复杂度仍为 O\texttt(|S|\texttt)。

part3 AC 代码

细节部分参考注释。

#include<bits/stdc++.h>
#define For(i,j,k) for(int i=j;i<=k;i++)
#define dFor(i,j,k) for(int i=j;i>=k;i--)
#define FIO(s) freopen(s".in","r",stdin);freopen(s".out","w",stdout);
#define int long long
const int inf=1e18;
const int Mmod=998244353;
const int MAXN=500005;
using namespace std;
namespace DEBUG{
    template<class T> void _debug(const char *s, T x) {cout<<s<<'='<<x<<endl;}
    template<class F, class... Nxt> void _debug(const char *s, F x, Nxt... nxt){
        int d=0;
        while(*s!=',' || d) d+=*s=='(', d-=*s==')', cout<<*s++;
        cout<<'='<<x<<',';
        _debug(s+1, nxt...);
  }
  #define debug(...) _debug(#__VA_ARGS__, __VA_ARGS__)
}
using namespace DEBUG;
int n,pre[MAXN],ans;
char s[MAXN];
struct kuohao{char ch;int id;};stack<kuohao>st,ST;
stack<int>head;
signed main(){
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    //FIO("");
    cin>>s+1,n=strlen(s+1);
    For(i,1,n){
        switch(s[i]){
            case '(':{
                if(!ST.empty()&&ST.top().id==head.top()) pre[i]=pre[head.top()]+1;
                else pre[i]=0;
                st.push(kuohao{'(',i});
                head.push(i);
                break;
            }
            case ')':{
                if(!st.empty()&&st.top().ch=='(') pre[i]=pre[st.top().id],ST.push(st.top()),ST.push(kuohao{')',i}),ans+=pre[st.top().id]+1,st.pop();
                else pre[i]=0,st.push(kuohao{')',i});
                head.push(i);
                break;
            }
            case '-':{
                if(!st.empty()&&st.top().id==head.top()) st.pop();
                else pre[ST.top().id]=0,ST.pop(),ans-=pre[ST.top().id]+1,st.push(ST.top()),ST.pop();
                head.pop();
                break;
            }
        }
        cout<<ans<<'\n';
    }
    return 0;
}

完结撒花~(樱花庄万岁)如果有写的不好的地方,欢迎私信作者或在下方留言,谢谢各位阅读与支持!