-
스택_백준_괄호의 값_2504Algorithm 2018. 8. 15. 13:53
for문으로 탐색 하면서 열린 괄호가 나올 경우 스택에 넣고 닫힌 괄호가 나올 경우 연속된 괄호열 중 최초의 결합된 괄호로부터 분배법칙으로 계산을 한다. 예를들어 (([])())경우 최초의 결합은 []이다. 이 경우 2*3이다. 이 계산은 2*((2*3)+2) = 2*(2*3) + 2*2로 계산을 할 수 있다.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889#include <iostream>#include <stack>#include <string>using namespace std;int main() {string input;stack <char> s;stack <char> tmp;int result = 0;int value = 0;cin >> input;s.push('-1'); // protect stack(empty) top access errorfor (int i = 0; i < input.size(); i++) {if (input[i] == '(') {s.push('(');}else if (input[i] == '[') {s.push('[');}else if (input[i] == ')') {if (s.top() != '(') {cout << 0 << endl;return 0;}//Not correctif (input[i - 1] == '(') {s.pop();tmp = s;value = 2;while (!tmp.empty()) {if (tmp.top() == '(') {value = 2 * value;}if (tmp.top() == '[') {value = 3 * value;}tmp.pop();}result += value;} // Calculateelse {s.pop();}}else if (input[i] == ']') {if (s.top() != '[') {cout << 0 << endl;return 0;}//Not correctif (input[i - 1] == '[') {s.pop();tmp = s;value = 3;while (!tmp.empty()) {if (tmp.top() == '(') {value = 2 * value;}if (tmp.top() == '[') {value = 3 * value;}tmp.pop();}result += value;}// Calculateelse {s.pop();}}else {cout << "Error" << endl;} // Input Error}s.pop();if (s.empty()) {cout << result << endl;}else {cout << 0 << endl;}// Not correctreturn 0;}// First, judge whether it is correct.If it is correct, judge separately by distribution law.cs 'Algorithm' 카테고리의 다른 글
스택_백준_키로거_5397 (0) 2018.08.15 스택_백준_탑_2493 (0) 2018.08.15 스택_백준_스택 수열_1874 (0) 2018.08.14 스택_백준_에디터_1406 (0) 2018.08.14 스택_백준_쇠막대기_10799 (0) 2018.08.14