백준 4949 - 균형잡힌 세상

황재진·2024년 3월 6일

백준

목록 보기
14/54
post-thumbnail

스택 자료구조를 활용하지만, 두 스택의 상태를 비교해야 하는 문제입니다.

만약 입력에 ( [ ) ] 이런식으로 들어오게 된다면, no를 출력해야 합니다. 이런 상황을 감지하기 위해 최근 체크한 괄호를 알 수 있는 스택을 하나 더 만들어 해당 상황이 온 경우 탈출해 no를 출력할 수 있도록 했습니다.

#include <iostream>
#include <string>

int main()
{
	std::string str;

	int stack_s[101];
	int stack_b[101];
	char stack_recent[101];
	int stack_s_top = -1;
	int stack_b_top = -1;
	int stack_recent_top = -1;

	std::getline(std::cin, str);
	while (str.compare(".") != 0)
	{
		for (int i = 0; i < 101; i++)
		{
			stack_s[i] = -1;
			stack_b[i] = -1;
			stack_recent[i] = ' ';
		}


		bool result = true;
		stack_s_top = -1;
		stack_b_top = -1;
		stack_recent_top = -1;
		for (auto iter = str.begin(); iter != str.end(); iter++)
		{
			if (*iter == '(')
			{
				stack_s_top++;
				stack_s[stack_s_top] = 1;
				stack_recent_top++;
				stack_recent[stack_recent_top] = '(';
			}
			else if (*iter == '[')
			{
				stack_b_top++;
				stack_b[stack_b_top] = 1;
				stack_recent_top++;
				stack_recent[stack_recent_top] = '[';
			}
			else if (*iter == ')')
			{
				if (stack_s_top == -1 || stack_recent[stack_recent_top] == '[')
				{
					result = false;
					break;
				}
				stack_s[stack_s_top] = -1;
				stack_s_top--;
				stack_recent[stack_recent_top] = ' ';
				stack_recent_top--;
			}
			else if (*iter == ']')
			{
				if (stack_b_top == -1 || stack_recent[stack_recent_top] == '(')
				{
					result = false;
					break;
				}
				stack_b[stack_b_top] = -1;
				stack_b_top--;
				stack_recent[stack_recent_top] = ' ';
				stack_recent_top--;
			}
		}

		if (result == true && stack_s_top == -1 && stack_b_top == -1)
			std::cout << "yes\n";
		else
			std::cout << "no\n";

		std::getline(std::cin, str);
	}

	return 0;
}

제 풀이가 가장 이상적인 풀이라고는 장담하지 못합니다. 분명 다른 분들이 작성하신 코드가 메모리 사용량이 더 적을 수도 있고 실행시간이 더 적을 수도 있습니다. 직접 풀어보시고 꼭 다른 분들의 풀이 또한 봐보셨으면 좋겠습니다.

profile
프로그래밍, 쉐이더 등 이것저것 다해보는 게임 개발자입니다

0개의 댓글