M - 13 HDU - 3351 (栈)
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.
The last line of the input is made of one or more ’-’ (minus signs.)
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.
}{ {}{}{} {{{} ---
1. 2 2. 0 3. 1
我是看网上题解的好吧并不难但是我无法理解题目(对不起原谅我关了原文衔接了) 把能匹配的删除掉那么最后剩下三种情况
{{{{{或者}}}}}或者}}}{{{
只有剩下这三种情况了 转换完剩下单个呢?是要补上去一个嘛?哎?我不晓得 题目看了半天都木有看到所以我不晓得
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> #include<stack> using namespace std; stack<char>s; char str[2005]; int main() { int t=1; while(gets(str),str[0]!='-') { int i,len=strlen(str); s.push(str[0]); for(int i=1;i<len;i++) { if(s.empty()==0) { if(s.top()=='{'&&str[i]=='}') s.pop(); else s.push(str[i]); }else { s.push(str[i]); } } int sum1=0,sum2=0; while(s.empty()==0) { if(s.top()=='{')sum1++; else sum2++; s.pop(); } int ans=(sum1+1)/2+(sum2+1)/2; printf("%d. %d\n", t++, ans); } return 0; }