넘치게 채우기

[BOJ] 10750 - Censoring 본문

PS/BOJ

[BOJ] 10750 - Censoring

riveroverflow 2025. 5. 26. 19:01
반응형

https://www.acmicpc.net/problem/10750

BOJ - Censoring

문제 유형: 문자열 처리, 스택

문제 난이도: Gold IV

시간 제한: 1초

메모리 제한: 256MB

 

문제

Farmer John has purchased a subscription to Good Hooveskeeping magazine for his cows, so they have plenty of material to read while waiting around in the barn during milking sessions. Unfortunately, the latest issue contains a rather inappropriate article on how to cook the perfect steak, which FJ would rather his cows not see (clearly, the magazine is in need of better editorial oversight).

FJ has taken all of the text from the magazine to create the string S of length at most 10^6 characters. From this, he would like to remove occurrences of a substring T of length <= 100 characters to censor the inappropriate content. To do this, Farmer John finds the _first_ occurrence of T in S and deletes it. He then repeats the process again, deleting the first occurrence of T again, continuing until there are no more occurrences of T in S. Note that the deletion of one occurrence might create a new occurrence of T that didn't exist before.

Please help FJ determine the final contents of S after censoring is complete.

 

주어진 문자열 s로부터 모든 t를 제거해야 한다. t를 제거한 뒤, 또 t가 있다면, 또 제거해야 한다.

모든 t를 제거한 뒤의 s를 출력하시오.

 

입력

첫째 줄에 s, 둘째 줄에 t가 주어집니다.

 

출력

연산이 끝난 s를 출력하시오.

 

풀이

스택에 한 글자씩 넣으면서, t의 맨 끝글자가 스택의 톱이라면, 스택의 글자들과 t의 글자들을 비교한다.

일치하면, 그 부분만큼 제거한다. 일치하지 않으면, 다시 복구한다.

 

스택에서 뺀 결과를 다시 문자열로 만들고 뒤집어준다.

 

코드

C++

#include <bits/stdc++.h>

using namespace std;

int main(int argc, char *argv[]) {
    string str, pat;
    cin >> str >> pat;

    stack<char> stk;
    for (int i = 0; i < str.size(); i++) {
        stk.push(str[i]);
        if (stk.size() >= pat.size() && stk.top() == pat.back()) {
            bool flag = true;
            stack<char> temp;
            for (int j = pat.size() - 1; j >= 0; j--) {
                if (stk.top() != pat[j]) {
                    flag = false;
                    break;
                }
                temp.emplace(stk.top());
                stk.pop();
            }
            if (!flag) {
                while (!temp.empty()) {
                    stk.emplace(temp.top());
                    temp.pop();
                }
            }
        }
    }

    string ans;
    while (!stk.empty()) {
        ans += stk.top();
        stk.pop();
    }
    reverse(ans.begin(), ans.end());
    cout << ans << "\n";

    return 0;
}
반응형

'PS > BOJ' 카테고리의 다른 글

[BOJ] 29726 - 숏코딩의 왕 브실이  (0) 2025.05.29
[BOJ] 1117 - 색칠 1  (0) 2025.05.27
[BOJ] 6209 - 제자리 멀리뛰기  (0) 2025.05.25
[BOJ] 1188 - 음식 평론가  (0) 2025.05.24
[BOJ] 1152 - 네 개의 소수  (0) 2025.05.23