나의 브을로오그으

[c++] 1541번 : 잃어버린 괄호 본문

알고리즘/BaekJoon

[c++] 1541번 : 잃어버린 괄호

__jhp_+ 2022. 6. 7. 14:39

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

 

1541번: 잃어버린 괄호

첫째 줄에 식이 주어진다. 식은 ‘0’~‘9’, ‘+’, 그리고 ‘-’만으로 이루어져 있고, 가장 처음과 마지막 문자는 숫자이다. 그리고 연속해서 두 개 이상의 연산자가 나타나지 않고, 5자리보다

www.acmicpc.net

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

struct ParseStack
{
	stack<int> stNum;
	stack<char> stOpt;
};

void Parse(ParseStack& ps, char* equation, int len)
{
	int sum = 0;
	for (int i = 0; i < len; ++i)
	{
		if (equation[i] == '+' || equation[i] == '-')
		{
			ps.stOpt.push(equation[i]);
			ps.stNum.push(sum);
			sum = 0;
		}
		else
		{
			sum *= 10;
			sum += equation[i] - '0';
		}
	}
	ps.stNum.push(sum);
	return;
}

int Calculation(ParseStack& ps)
{
	int result = 0;
	int sum = 0;
	while (ps.stOpt.empty() == false)
	{
		int num = ps.stNum.top();
		ps.stNum.pop();

		char opt = ps.stOpt.top();
		ps.stOpt.pop();
		if (opt == '-')
		{
			sum = ~(sum + num) + 1;
			result += sum;
			sum = 0;
		}
		else
		{
			sum += num;
		}
	}
	return result + sum + ps.stNum.top();
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);

	char equation[51] = { 0, };
	ParseStack ps;
	int result = 0;
	cin >> equation;

	int len = 0;
	while (equation[len] != '\0') { ++len; }

	Parse(ps, equation, len);
	result = Calculation(ps);
	cout << result << '\n';

	return 0;
}