스택 기반 알고리즘 문제 분석 및 해결

문제 1: 소수의 숫자 게임 (P1427)

스택의 후입선출(LIFO) 특성을 활용하여 입력된 숫자를 역순으로 출력하는 문제. 초기 코드에서 size() 호출 후 pop()을 수행하면서 크기 계산 오류가 발생했다.

#include <bits/stdc++.h>
using namespace std;

stack<int> num_stack;

int main() {
    int value;
    while (cin >> value && value != 0) {
        num_stack.push(value);
    }

    // pop 이후 크기를 측정해야 함
    num_stack.pop();
    int total_size = num_stack.size();

    for (int i = 0; i < total_size; ++i) {
        cout << num_stack.top() << ' ';
        num_stack.pop();
    }
    return 0;
}

문제 2: 괄호 매칭 검사 (P1739)

여는 괄호는 스택에 저장하고, 닫는 괄호는 스택에서 짝을 찾아 제거. 스택이 비어있으면 불일치로 판단.

#include <bits/stdc++.h>
using namespace std;

stack<char> bracket_stack;

int main() {
    char ch;
    while (cin.get(ch) && ch != '@') {
        if (ch == '(') {
            bracket_stack.push(ch);
        } else if (ch == ')') {
            if (bracket_stack.empty()) {
                cout << "NO";
                return 0;
            }
            bracket_stack.pop();
        }
    }

    cout << (bracket_stack.empty() ? "YES" : "NO");
    return 0;
}

문제 3: 스택 기본 연산 구현 (B3614)

스택의 다양한 연산(삽입, 삭제, 조회, 크기 확인)을 구현하며, 빈 상태 처리를 정확히 해야 한다.

#include <bits/stdc++.h>
#define ull unsigned long long
using namespace std;

stack<ull> stk;

int main() {
    ull test_cases;
    cin >> test_cases;

    while (test_cases--) {
        ull n;
        cin >> n;

        // 스택 초기화
        while (!stk.empty()) stk.pop();

        for (ull i = 0; i < n; ++i) {
            string operation;
            cin >> operation;

            if (operation == "push") {
                ull val;
                cin >> val;
                stk.push(val);
            } else if (operation == "pop") {
                if (!stk.empty()) stk.pop();
                else cout << "Empty" << endl;
            } else if (operation == "query") {
                if (!stk.empty()) cout << stk.top() << endl;
                else cout << "Anguei!" << endl;
            } else if (operation == "size") {
                cout << stk.size() << endl;
            }
        }
    }
    return 0;
}

문제 4: 대소문자 조합 처리 (U419333)

대소문자가 상호보완되는 문자쌍을 스택을 통해 제거하는 문제. 현재까지 완성되지 않음. 핵심은 동일한 알파벳의 대소문자를 비교하고, 일치하면 제거, 아니면 변환하여 스택에 추가.

문제 5: 문자열에서 "ABC" 제거하기 (ABC328D)

문자열에서 "A", "B", "C" 순서로 나타나는 경우를 스택을 통해 제거. "C"가 등장할 때 앞에 "B"와 "A"가 올 경우 제거, 그렇지 않으면 다시 삽입.

#include <bits/stdc++.h>
using namespace std;

stack<char> char_stack;

int main() {
    string s;
    cin >> s;

    for (char c : s) {
        if (c == 'A') {
            char_stack.push(c);
        } else if (c == 'B') {
            char_stack.push(c);
        } else if (c == 'C') {
            if (char_stack.size() >= 2) {
                char b = char_stack.top(); char_stack.pop();
                char a = char_stack.top(); char_stack.pop();
                if (b == 'B' && a == 'A') continue;
                else {
                    char_stack.push(a); char_stack.push(b);
                    char_stack.push('C');
                }
            } else {
                char_stack.push(c);
            }
        }
    }

    string result = "";
    while (!char_stack.empty()) {
        result = char_stack.top() + result;
        char_stack.pop();
    }
    cout << result << endl;
    return 0;
}

문제 6: 후위 표기법 계산 (P1981)

후위 표기식(Reverse Polish Notation)을 스택을 이용해 계산. 곱셈은 스택에서 두 개를 꺼내 곱한 후 결과를 다시 넣고, 덧셈은 단순히 스택에 푸시.

#include <bits/stdc++.h>
using namespace std;

stack<int> calc_stack;

int main() {
    int operand;
    cin >> operand;
    operand %= 10000;
    calc_stack.push(operand);

    char op_char;
    int next_operand;
    while (cin >> op_char >> next_operand) {
        if (op_char == '*') {
            int top_val = calc_stack.top();
            calc_stack.pop();
            calc_stack.push((next_operand * top_val) % 10000);
        } else {
            calc_stack.push(next_operand % 10000);
        }
    }

    int total = 0;
    while (!calc_stack.empty()) {
        total += calc_stack.top();
        total %= 10000;
        calc_stack.pop();
    }

    cout << total << endl;
    return 0;
}

태그: 스택 후위 표기법 알고리즘 C++ 문제 해결

6월 21일 23:38에 게시됨