1000. Clumsy Cows

1000. Clumsy Cows
Total:	71	Accepted:	33



Time Limit: 1sec    Memory Limit:256MB
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:
)(
())(
((())))
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
 Copy sample input to clipboard
())(
Sample Output
2


这题在做比赛的时候自己没有想出来,后来请教了一下教主,然后告诉了思路,但是估计自己还是没有听懂,然后和同学分享了一下
不一会儿同学就按照教主的思路AC了,然后帮我讲了一下思路,擦擦,原来是这样,就是把配对的删掉,具体见代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const int N=100005;
char x[N];
int main()
{
    while(scanf("%s",x)!=EOF)
    {
        int xlen=strlen(x);
        int sum=0,sum1=0;
        for(int i=0; i<xlen; i++)
        {
            if(x[i]=='(')
            {
                sum++;
            }
            else if(sum&&x[i]==')')
            {
                sum--;
            }
            else if(sum==0&&x[i]==')')
            {
                sum++;
                sum1++;
                x[i]='(';
            }
        }
        printf("%d\n",sum/2+sum1);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值