[백준 실버2] 1541 : 잃어버린 괄호

수민이슈·2023년 9월 21일
0

[C++] 코딩테스트

목록 보기
65/116
post-thumbnail

🖊️ 문제

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


🖊️ 풀이

Greedy라고는 하는데,,

일단 전반적인 문제에서,
연산자(+ or -)를 만날 때 까지의 입력을 int형으로 저장하고,
괄호 만나거나 입력이 끝나면 연산해주면 된다.
여기서 최소를 만들려면, -연산자가 나오고 다음 -연산자가 나올 때까지 괄호를 쳐주면 된다.
-기준 마이너스, +, -연산자만 있을 때면
그냥 -가 나오면 계속 마이너스 해주면 된다.

그래서 -가 있는지 판별해주는 것만 있으면 된다.

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int main()
{
	cin.tie(0);
	cout.tie(0);
	ios::sync_with_stdio(false);

	string input;
	cin >> input;

	int answer = 0;
	int num = 0;
	string temp = "";
	bool isMinus = false;
	for (int i = 0; i < input.size(); i++) {
		if (isdigit(input[i])) {
			temp += input[i];
		}
		else {
			num = stoi(temp);
			if (!isMinus) answer += num;
			else answer -= num;

			if (input[i] == '-') isMinus = true;

			temp = "";
			num = 0;
		}
	}
	num = stoi(temp);
	if (!isMinus) answer += num;
	else answer -= num;
	cout << answer << endl;
}

0개의 댓글