zoukankan      html  css  js  c++  java
  • BZOJ 3016 [Usaco2012 Nov]Clumsy Cows:贪心

    题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=3016

    题意:

      给你一个括号序列,问你至少修改多少个括号,才能使这个括号序列合法。

    题解:

      贪心。

      cnt表示当前已经攒了多少个左括号。

      从左往右枚举每一个括号:

        (1)如果为左括号,则cnt++。

        (2)如果为右括号,且cnt > 0,则cnt--。表示消去了一个左括号。

        (3)如果为右括号,且cnt <= 0,则cnt++,ans++。因为此时一定要改。

      最后ans还要加上cnt/2,因为在剩下的左括号中,至少要将一半改为右括号。

    AC Code:

     1 #include <iostream>
     2 #include <stdio.h>
     3 #include <string.h>
     4 
     5 using namespace std;
     6 
     7 int cnt=0;
     8 int ans=0;
     9 string s;
    10 
    11 int main()
    12 {
    13     cin>>s;
    14     for(int i=0;i<s.size();i++)
    15     {
    16         if(s[i]=='(') cnt++;
    17         else if(cnt>0) cnt--;
    18         else cnt++,ans++;
    19     }
    20     cout<<ans+cnt/2<<endl;
    21 }
  • 相关阅读:
    C#数组添加元素
    C#数组排序方法
    C#遍历数组
    C#动态数组ArrayList
    C#传递数组参数
    基础题(四)
    基础题(三)
    CMDB概述(二)
    CMDB概述(一)
    Django(基础篇)
  • 原文地址:https://www.cnblogs.com/Leohh/p/7631860.html
Copyright © 2011-2022 走看看