跳到正文

题解

题解:P15236 [NHSPC 2025] 括号问题

ryf2011约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年2月10日
更新
2026年2月10日
篇幅
约 2 分钟
题目
P15236

版本

  1. v1当前

注:题解无 AI 生成。

1.括号序列的满足条件

一个由括号构成的序列 P=p1p2p3⋯pnP=p_1p_2p_3\cdots p_n 为格式正确,若同时满足以下两个条件:

  1. 由左到右扫描 p1p_1 到 pnp_n,在过程中任一位置的右括号 ) 的数量都不超过左括号 ( 的数量。
  2. 序列中左括号的总数等于右括号的总数。

根据这个条件,我们可以得到:

  • () 是合法序列;
  • )( 不是合法序列,因为在扫描到 p1p_1 时,右括号数量超过左括号数量;
  • ((()))() 是合法序列,因为题目并未提及左括号数量大于右括号数量的情况。

2.过程

  1. 不需要使用栈,从左到右遍历字符串。同时记录左括号和右括号的数量,任意时刻若右括号数量大于左括号数量,则令右括号数量等于左括号数量,答案加 11。
  2. 最终计算答案时,加上左括号数量减去右括号数量的绝对值,这样就能满足判定的第 22 个条件,即两种括号总数相等。

3.代码

C++
#include<bits/stdc++.h>
using namespace std;
const int max_n=1e5+2;
int n;
int nowl,nowr,ans;
char s[max_n];
int main(){
    scanf("%d",&n);
    scanf("%s",s+1);
    for(int i=1;i<=n;i++){
        if(s[i]=='('){
            nowl++;
        }
        else{
            nowr++;
        }
        if(nowr>nowl){ //不满足条件,答案 +1
            nowr=nowl;
            ans++;
        }
    }
    ans+=abs(nowl-nowr); //使两种括号数量相等
    printf("%d\n",ans);
    return 0;
}

4.后记

更多内容,请移步至:

  1. Luogu ryf2011\color{red}\texttt{Luogu ryf2011};
  2. cnblogs(博客园) cnblogs2011ryf\color{orange}\texttt{cnblogs(博客园) cnblogs2011ryf}。
原文