251 words
1 minutes
[BOJ] 괄호의 값
TimeLimit | MemoryLimit | Condition | TAG |
---|---|---|---|
1s | 128MB | (1 ≤ string_length ≤ 30) | Data Structure |
그냥 간단한 stack 구현 문제였습니다.
정답 코드
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <sstream>
#include <iomanip>
#include <string>
#include <numeric>
#include <unordered_set>
#include <unordered_map>
#include <climits>
#include <math.h>
using namespace std;
using ll = unsigned long long;
using ld = long double;
//ll MOD = 1'000'000'007;
ll MOD = 1'000'000'000;
//ll MOD = 1.8446744074E19;
struct info {
char c;
int val;
};
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
vector<info> stack;
string input;
cin >> input;
for(int i = 0; i < input.size(); i++){
if(stack.empty()){ stack.push_back({input[i], 0}); continue;}
char current = input[i];
info pre = stack.back();
if(pre.c== '(' && current == ')'){
stack.pop_back();
stack.push_back({0, 2});
}else if(pre.c == '[' && current == ']'){
stack.pop_back();
stack.push_back({0, 3});
}else if(pre.c == 0 && (current == ')' || current == ']')){
char limit = current ==')' ? '(' : '[';
int result = stack.back().val * (current == ')' ? 2 : 3);
stack.pop_back();
if(stack.empty() || stack.back().c != limit){
cout << 0;
return 0;
}
stack.pop_back();
stack.push_back({0, result});
}else{
stack.push_back({current, 0});
}
if(!stack.empty() && stack.back().c == 0){
int result = 0;
while(!stack.empty() && stack.back().c == 0) {
result += stack.back().val;
stack.pop_back();
}
stack.push_back({0, result});
}
}
int result = 0;
while(!stack.empty() && stack.back().val != 0){
result += stack.back().val; stack.pop_back();
}
if(stack.size() > 0) cout << 0;
else cout << result;
return 0;
}
/*
([()()()()]()()()())
*/