• USACO Clumsy Cows


    洛谷 P3056 [USACO12NOV]笨牛Clumsy Cows

    洛谷传送门

    JDOJ 2323: USACO 2012 Nov Silver 1.Clumsy Cows

    JDOJ传送门

    Description

    Problem 1: Clumsy Cows [Brian Dean, 2012]

    Bessie the cow is trying to type a balanced string of parentheses into her
    new laptop, but she is sufficiently clumsy (due to her large hooves) that
    she keeps mis-typing characters. Please help her by computing the minimum
    number of characters in the string that one must reverse (e.g., changing a
    left parenthesis to a right parenthesis, or vice versa) so that the string
    would become balanced.

    There are several ways to define what it means for a string of parentheses
    to be "balanced". Perhaps the simplest definition is that there must be
    the same total number of ('s and )'s, and for any prefix of the string,
    there must be at least as many ('s as )'s. For example, the following
    strings are all balanced:

    ()
    (())
    ()(()())

    while these are not:

    )(
    ())(
    ((())))

    Input

    * Line 1: A string of parentheses of even length at most 100,000
    characters.

    Output

    * Line 1: A single integer giving the minimum number of parentheses
    that must be toggled to convert the string into a balanced
    string.

    Sample Input

    ())(

    Sample Output

    2

    HINT

    OUTPUT DETAILS:

    The last parenthesis must be toggled, and so must one of the two middle
    right parentheses.

    题目大意:

    给出一个偶数长度的括号序列,问最少修改多少个括号可以使其平衡。

    我再多解释一下啥叫括号平衡,就是左括号和右括号的数量相等。

    题解:

    这道题是栈结构的练手题。

    其实题意也很简单,就是一个模拟,但是我们可以用栈的数据结构使得这个东西变得更加简洁明了。

    我们可以考虑一下“消消乐”的思想(自编名词

    就是左括号正常进栈,如果碰到右括号且栈不为空就弹出来跟他匹配,如果碰到右括号而且栈空了,那就说明没有东西和他匹配,我们就需要把这个东西改成左括号压进栈,同时ans++。

    注意,最后的时候,我们还要判一下这个栈是否为空,如果不为空的话说明还是不平衡,那么还需要把ans+栈内元素个数除以2.

    原理很简单了/

    代码:

    #include<cstdio>
    #include<cstring>
    #include<stack>
    using namespace std;
    char s[100001];
    stack<char> st;
    int ans;
    int main()
    {
        scanf("%s",s+1);
        int len=strlen(s+1);
        for(int i=1;i<=len;i++)
        {
            if(s[i]=='(')
                st.push(s[i]);
            if(s[i]==')')
            {
                if(st.empty())
                {
                    st.push('(');
                    ans++;
                }
                else
                    st.pop();
            }
        }
        if(!st.empty())
            ans+=st.size()/2;
        printf("%d",ans);
        return 0;
    }
    
  • 相关阅读:
    POJ 2559 Largest Rectangle in a Histogram(单调栈)
    POJ 1631 Bridging signals(最长上升子序列LIS)
    POJ 3977 Subset(二分+折半枚举)
    POJ 1742 Coins(dp多重背包)
    【洛谷P2622】关灯问题II【BFS】【状压】
    【洛谷P2622】关灯问题II【BFS】【状压】
    【洛谷P4281】紧急集合 / 聚会【LCA】
    【洛谷P4281】紧急集合 / 聚会【LCA】
    【洛谷P2420】让我们异或吧【DFS】
    【洛谷P2420】让我们异或吧【DFS】
  • 原文地址:https://www.cnblogs.com/fusiwei/p/11294163.html
Copyright © 2020-2023  润新知