hades

[Baekjoon] 9935๋ฒˆ: ๋ฌธ์ž์—ด ํญ๋ฐœ ๋ณธ๋ฌธ

๐Ÿ‘Š PS/Algorithm

[Baekjoon] 9935๋ฒˆ: ๋ฌธ์ž์—ด ํญ๋ฐœ

hades1 2024. 9. 4. 21:48

๐Ÿฅ… ๋ฌธ์ œ

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

 

๐Ÿ” ์„ค๊ณ„

๋ฌธ์ž์—ด์˜ ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ๋ฆฌ๋ฉด์„œ, ํญ๋ฐœ ๋ฌธ์ž์—ด๊ณผ ์ผ์น˜ํ•˜๋Š” ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์ด ๋งŒ๋“ค์–ด์ง€๋ฉด, ๋งจ ์œ„๋ถ€ํ„ฐ ํญ๋ฐœ์‹œ์ผœ์•ผ ํ•˜๋ฏ€๋กœ, ์Šคํƒ์„ ์ด์šฉํ•œ๋‹ค๋Š” ๊ฒƒ์€ ์‰ฝ๊ฒŒ ํŒŒ์•…ํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.

 

ํญ๋ฐœ ๋ฌธ์ž์—ด๊ณผ ์ผ์น˜ํ•˜๋ฉด ํ˜„์žฌ ์ธ๋ฑ์Šค์—์„œ ํญ๋ฐœ ๋ฌธ์ž์—ด์—์„œ ์ผ์น˜ํ•œ ์ธ๋ฑ์Šค๋ฅผ save์— ์ €์žฅํ•˜๊ณ , ๋‹ค์Œ ํƒ์ƒ‰ํ•  ์ธ๋ฑ์Šค(cur_idx)๋ฅผ 1 ์ฆ๊ฐ€์‹œํ‚ค๋ฉด์„œ ํญ๋ฐœ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด์™€ ์ผ์น˜ํ•˜๋ฉด ํญ๋ฐœ์‹œํ‚ค๋Š” ๋ฐฉ์‹์œผ๋กœ ์„ค๊ณ„ํ–ˆ๋‹ค.

 

์ดˆ๊ธฐ ์„ค๊ณ„์—์„œ์˜ ๋ฌธ์ œ์ ์€ ์Šคํƒ์— ๋ฌธ์ž๋งŒ ๋‹ด์•˜๊ธฐ ๋•Œ๋ฌธ์— ํญ๋ฐœํ•˜๊ณ  ๋‚œ ํ›„, ๋‹ค์Œ ํƒ์ƒ‰ํ•  ์ธ๋ฑ์Šค๋ฅผ ํญ๋ฐœ ๋ฌธ์ž์—ด์ด ์™„์„ฑ๋œ ์œ„์น˜์—์„œ ํญ๋ฐœ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ ๋บ€ ์ธ๋ฑ์Šค์—์„œ์˜ save ๊ฐ’๊ณผ ๊ฐ™์ด ์ž˜ ๋ชป ๊ตฌํ–ˆ์—ˆ๋‹ค. ํ•˜์ง€๋งŒ ์ด๋Ÿฐ ๊ฒฝ์šฐ, 

 

abaabcdbcdcd

abcd

 

์™€ ๊ฐ™์ด ์ค‘๊ฐ„์— ๋‘ ๋ฒˆ ์ด์ƒ ํญ๋ฐœ์ด ์ด๋ฃจ์–ด์ง€๋Š” ๊ฒฝ์šฐ์— ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š๋‹ค.

 

๋‹จ์ˆœํ•˜๊ฒŒ ์Šคํƒ์— ๋ฌธ์ž์™€ ๊ทธ ๋ฌธ์ž์˜ ์œ„์น˜๋ฅผ ๊ฐ™์ด ์ €์žฅํ•˜๊ณ , ๊ทธ ์œ„์น˜์—์„œ์˜ save๊ฐ’ + 1์ด ๋‹ค์Œ ํƒ์ƒ‰ํ•  ์ธ๋ฑ์Šค์ด๋‹ค.

 

๐Ÿ‘Š ํ’€์ด

#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

string original, boom;
stack<pair<char, int>> s;
vector<int> save(1000000, -1);
int cur_idx = 0, temp_idx;

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);	
	cin >> original >> boom;
	int original_length = original.length();
	int boom_length = boom.length();
	for (int i = 0; i < original_length; i++) {
		s.push({ original[i], i });
		if (s.top().first == boom[cur_idx]) {
			save[i] = cur_idx;
			cur_idx += 1;
			if (cur_idx == boom_length) {
				for (int j = 0; j < boom_length; j++) {
					s.pop();
				}
				if (s.empty()) {
					cur_idx = 0;
				}
				else {
					cur_idx = save[s.top().second] + 1;
				}
				
			}
		}
		else {
			cur_idx = 0;
			if (s.top().first == boom[cur_idx]) {
				save[i] = cur_idx;
				cur_idx += 1;
			}
		}
	}

	string result = "";

	if (s.empty()) {
		cout << "FRULA" << "\n";
		return 0;
	}

	while (!s.empty()) {
		result += s.top().first;
		s.pop();
	}
	reverse(result.begin(), result.end());
	cout << result << "\n";

	return 0;
}