F---宋飞正传

Posted 平凡的神灯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了F---宋飞正传相关的知识,希望对你有一定的参考价值。

题目:
 
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---宋飞正传的主要内容,如果未能解决你的问题,请参考以下文章

F - 宋飞正传

VSCode自定义代码片段——声明函数

VSCode自定义代码片段8——声明函数

If you want something, go get it. Period.---献给《阿甘正传》、《当幸福来敲门》

缺少 SQL SERVER 2014 代码片段

PHP 代码片段