3016: [usaco 128 Nov] Clumsy cowstime limit: 1 sec memory limit: MB
Submit: 71 solved: 52
[Submit] [Status] Descriptionbessie 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 wocould 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 hour ('s as)'s. for example, the following strings are all balanced :() () while these are not :)(())(((()))) problem description given length:
NEach time you modify a sequence of parentheses, you can modify the brackets of a position. If this sequence is '(', it is changed to ')', if it is ')', then, modify it to '(' and ask the minimum number of modifications to make the sequence of original parentheses legal. Where: ① () is legal; ② If
AIs legal, then (
A) Is valid. ③ if
A,
BAre valid, then
ABIt is legal. The input length is
NParentheses. The minimum number of output modifications. Sample input ())(
Sample output 2
Example
Change to (), where the red part indicates the modified parentheses.
Data range
100% of the data meets the following requirements: 1 <= n <= 100,000. Hint Source
Silver
Question: Good greed.
Use s to record the number of '(') in front of the record ('s ++, read')'s --
S <0 indicates that there is no '(' more ')', you need to change ')' to '(', so S + = 2, ANS ++
Last if s! When the value is 0, we need to change half of '(' to ')', that is, ANS + = S/2.
When I think about it, I don't dare to think about it, so I didn't think about t_t.
Code:
1 #include<cstdio> 2 int n,s,ans; 3 char ch; 4 int main() 5 { 6 while (scanf("%c",&ch)!=EOF) 7 { 8 if (ch==‘\n‘)break; 9 if (ch==‘(‘)s++;10 if (ch==‘)‘)11 {12 s--;13 if (s<0){s+=2;ans++;}14 }15 }16 ans+=s/2;17 printf("%d",ans);18 }
View code
Bzoj3016: [usaco2012 Nov] Clumsy cows