码迷,mamicode.com
首页 > 其他好文 > 详细

F---宋飞正传

时间:2017-07-21 23:26:44      阅读:416      评论:0      收藏:0      [点我收藏+]

标签:art   ane   init   ring   size   mem   ems   this   pac   

题目:
 
I’m out of stories. For years I’ve been writing stories, some rather silly, just to make simple problems look difficult and complex problems look easy. But, alas, not for this one. 
You’re given a non empty string made in its entirety from opening and closing braces. Your task is to find the minimum number of “operations” needed to make the string stable. The definition for being stable is as follows: 
1. An empty string is stable. 
2. If S is stable, then {S} is also stable. 
3. If S and T are both stable, then ST (the concatenation of the two) is also stable. 
All of these strings are stable: {}, {}{}, and {{}{}}; But none of these: }{, {{}{, nor {}{. 
The only operation allowed on the string is to replace an opening brace with a closing brace, or visa-versa. 

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 }

 




F---宋飞正传

标签:art   ane   init   ring   size   mem   ems   this   pac   

原文地址:http://www.cnblogs.com/shendeng23/p/7219886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!