zoukankan      html  css  js  c++  java
  • 【BZOJ】3016: [Usaco2012 Nov]Clumsy Cows 贪心 单调栈

    Description

    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:
    )(
    ())(
    ((())))
     
    问题描述
    给定长度为n的一个括号序列,每次修改可以修改一个位置的括号,若这个括号为’(‘,则修改为’)’,若这个括号为’)’,则修改为’(‘,问最少修改多少个使得原括号序列合法。
    其中:
        ()是合法的;
        A是合法的,则(A)是合法的;
        AB都是合法的,则AB是合法的。
     

    Input

     一个长度为n个括号序列。
     

    Output

     
    最少的修改次数。
     

    Sample Input

    ())(

    Sample Output

    2
    样例说明
    修改为()(),其中红色部分表示修改的括号。

    数据范围
    100%的数据满足:1 <= n <= 100,000。

    HINT

    Source

    Silver

    题解:

      这题直接乱搞。。我们知道,对于每个合法的括号序列,这个序列的任意一个位置的之前的所有的左括号的数目都是要大于等于右括号的数目的。所以我们利用这条性质,可以用一个计数器来模拟一个类似单调栈的东西,每次进来一个右括号,都用它来抵消左括号,当计数器等于0,即相当于所有的左括号都匹配了一个右括号的时候,又来了一个右括号,那么这时就需要改变括号。最后的答案要再加上多出来的左括号的数目的一半。

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <algorithm>
     4 #include <cstring>
     5 using namespace std;
     6 const int MAXN=10001;
     7 int main(int argc, char *argv[])
     8 {
     9     int d=0,n,i;
    10     int ans=0;
    11     char x;
    12     while(cin>>x)
    13     {
    14         if(x=='(') d++; 
    15         else if(x==')'&&d>=1) d--;
    16         else if(x==')'&&d==0) ans++,d++;
    17     }
    18     ans+=(d+1)/2;
    19     printf("%d
    ",ans);
    20     return 0;
    21 }

  • 相关阅读:
    Win10新建文件不自动刷新
    解决 Win10 系统新建文件夹后需手动刷新才能显示
    新建的文件需要刷新才能看见怎么办?
    win7、win10系统电脑开机后小键盘灯不亮怎么办?
    VMware Workstation 将虚拟机挂起后,电脑会很卡,SCSI转换成IDE就可以了
    如何把VMware Workstation使用的虚拟SCSI磁盘转换成虚拟IDE硬盘
    bat批处理文件怎么将路径添加到path环境变量中
    在Windows下使用svn命令行教程及svn命令行的解释
    php正确解码javascript中通过escape编码后的字符
    采集/自动登录啊都可以用这两个方法实现 asp.net
  • 原文地址:https://www.cnblogs.com/BeyondW/p/5832083.html
Copyright © 2011-2022 走看看