标签:art ane init ring size mem ems this pac
InputYour program will be tested on one or more data sets. Each data set is described on a single line. The line is a non-empty string of opening and closing braces and nothing else. No string has more than 2000 braces. All sequences are of even length.
The last line of the input is made of one or more ’-’ (minus signs.)
OutputFor each test case, print the following line:
k. N
Where k is the test case number (starting at one,) and N is the minimum number of operations needed to convert the given string into a balanced one.
Note: There is a blank space before N.
Sample Input
}{ {}{}{} {{{} ---
Sample Output
1. 2 2. 0 3. 1
解题思路:
很显然这一题要使用栈来储存括号。
难点:要使改变的括号最少。如果输入的是’{‘则放入栈内,如果输入的是’}‘则要看栈顶是否是’{‘,有,则删除栈顶括号;没有,则把’}’变为‘{’放入栈顶(改变次数加一)。结束时栈内只可能存在这种‘{’括号,则只需要再改变(‘{’个数)/2个括号即可。
1 #include <iostream> 2 #include <stack> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6 7 int main() 8 { 9 int i,k,n,t=1,ans,j; 10 char a[2002]; 11 stack<char>s; 12 13 while (1) 14 { 15 memset(a,0,sizeof(a)); 16 gets(a);ans=0; 17 if (a[0]==‘-‘)break; 18 for (j=0;j<strlen(a);j++) 19 { 20 if (a[i]==‘}‘) 21 { 22 if (s.top()==‘{‘) 23 s.pop(); 24 if (!s.size()) //如果栈内元素个数为0 25 { 26 a[i]=‘{‘; //改变括号 27 ans++; 28 } 29 } 30 if (a[i]==‘{‘)s.push(a[i]); 31 } 32 k=s.size()/2; 33 ans+=k; 34 cout <<t<<". "<<ans<<endl; 35 t++; 36 } 37 return 0; 38 }
要
标签:art ane init ring size mem ems this pac
原文地址:http://www.cnblogs.com/shendeng23/p/7219886.html