# 3016: [Usaco2012 Nov]Clumsy Cows

169人阅读 评论(0)

## 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:
)(
())(
((())))

()是合法的；
A是合法的，则(A)是合法的；
AB都是合法的，则AB是合法的。

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

())(

## Sample Output

2

100%的数据满足：1 <= n <= 100,000。

## Source

Silver

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

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN=10001;
int main(int argc, char *argv[])
{
int d=0,n,i;
int ans=0;
char x;
while(cin>>x)
{
if(x=='(') d++;
else if(x==')'&&d>=1) d--;
else if(x==')'&&d==0) ans++,d++;
}
ans+=(d+1)/2;
printf("%d\n",ans);
return 0;
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：11609次
• 积分：570
• 等级：
• 排名：千里之外
• 原创：47篇
• 转载：0篇
• 译文：0篇
• 评论：2条
神犇友链
文章存档
最新评论