一本通 1572:括号配对

\(\quad\) 一开始以为这真是个括号匹配,写了个栈,甚至用了 STL。

#include <stdio.h>
#include <string.h>

#include <stack>

int ans = 0, len;
char str[1 << 7];

std::stack<bool>stack;

int main(){
    scanf("%s", str);
    len = strlen(str);
    for(int i = 0; i < len; ++i)
        if(str[i] == '(' || str[i] == '[')
            stack.push(str[i] == '(');
        else{
            if(str[i] == ')'){
                if(stack.empty() || !stack.top())
                    ++ans;
                else
                    stack.pop();
            }
            else{
                if(stack.empty() || stack.top())
                    ++ans;
                else
                    stack.pop();
            }
        }
    ans += stack.size();
    printf("%d\n", ans);
    return 0;
}

\(\quad\) 结果只有 \(40\) 分。想了好久,想出了反例。

([)

\(\quad\) 以上字符串一个匹配的括号都没有,但实际上只需要增加 \(1\) 个字符。正确的做法是:
\(\quad\) \(\bullet\)\(dp_{i,j}\) 表示在 \([i,j]\) 范围内,最多有多少对匹配括号。
\(\quad\) \(\bullet\) \(dp_{i,j} = dp_{i + 1, j - 1} | \,s_i\)\(s_j\) 匹配。
\(\quad\) 最终答案就是 \(n - 2 \cdot dp_{1,n}\)

猜你喜欢

转载自www.cnblogs.com/natsuka/p/12297720.html