【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\n",ans);
20     return 0;
21 }

 


 

posted @ 2016-09-02 08:35  BeyondW  阅读(275)  评论(0编辑  收藏  举报