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 }

 

posted @ 2017-10-06 17:37  Leohh  阅读(153)  评论(0编辑  收藏  举报