http://tjuacm.chaosheng.top/problem.php?id=1254
一开始直接这么写,能过样例,但是在vj上提交WA
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
int main(){
string s;
while(cin >> s){
int n = s.size();
int i = 0, count = 0;
while(i < n && s[i] != 'B'){
if(s[i] == '('){
count++;
}
i++;
}
printf("%d\n", count);
}
return 0;
}注意这里B之前可能出现空盒,这个是可以不拆开的。所以算最小次数要减去左右括号配对的。
用栈实现,最后栈的大小就是所求。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <stack>
using namespace std;
int main(){
string s;
while(cin >> s){
stack<char> brac;
int n = s.size();
int i = 0;
while(i < n && s[i] != 'B'){
if(brac.empty()){
brac.push(s[i]);
}else{
if(brac.top() == '(' && s[i] == ')'){
brac.pop();
}else{
brac.push(s[i]);
}
}
i++;
}
printf("%d\n", brac.size());
}
return 0;
}
京公网安备 11010502036488号