본문 바로가기
알고리즘/그리디

백준 1541번 : 잃어버린 괄호

by Jason95 2021. 1. 10.

문제 링크 : www.acmicpc.net/problem/1541

내 풀이(2021.1.10) :

#include <iostream>
#include <string>

using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	
	string str; cin >> str;
	int result = 0;
	int idx = 0;
	bool minus = false;
	bool first = true;
	int i = 0;
	for (; i < str.size(); i++) {
		if (str[i] != '+' && str[i] != '-') continue;
		if (!minus && str[i]=='+') {
			result += stoi(str.substr(idx, i - idx));
			idx = i + 1;
		}
		else {
			if (first) {
				result += stoi(str.substr(idx, i - idx));
				first = false;
			}
			else result -= stoi(str.substr(idx, i - idx));
			idx = i + 1;
		}
		if (str[i] == '-') minus = true;
	}
	if (!minus) {
		result += stoi(str.substr(idx, i - idx));
	}
	else {
		result -= stoi(str.substr(idx, i - idx));
	}
	cout << result;

	return 0;
}

풀이가 너무 복잡하다.

2가지 원인이 있는데,

하나는 string 타입의 끝에는 '\0'(=NULL)이 저장되어 있다는 사실을 몰랐고

또 하나는 for문을 돌 때마다 문자 단위로 쌓아가는 아이디어를 못 떠올렸다.

이 2가지 아이디어를 적용한 알고리즘은 다음과 같다.

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

int main(void) {
	string str; cin >> str;
	bool minus = false;
    int ans = 0;
	string temp;
	for (int i = 0; i < str.size() + 1; i++) {
		if (str[i] == '+' || str[i] == '-' || str[i] == '\0') {
			if (minus) ans -= stoi(temp);
			else ans += stoi(temp);
			temp.clear();
			if (str[i] == '-') minus = true;
		}
		else {
			temp += str[i];
		}
	}
	cout << ans;
	return 0;
}

출처 : www.acmicpc.net/source/25113620

'알고리즘 > 그리디' 카테고리의 다른 글

백준 1931번 : 회의실 배정  (0) 2021.01.09
백준 11047번 : 동전 0  (0) 2021.01.08
백준 13305번 : 주유소  (0) 2021.01.06