Notice
Recent Posts
Recent Comments
Link
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

hwooo

BOJ (C/C++) 1541번: 잃어버린 괄호 본문

Study/Algorithm

BOJ (C/C++) 1541번: 잃어버린 괄호

hwooo 2023. 5. 1. 18:20


풀이

- 문제에서 양수를 사용한다하였으니 문자열의 맨 앞에 부호가 오는 경우는 생각하지 않음
- 음수가 1번 나오면 괄호를 이용하여 뒤의 양수들도 모두 음수로 만들 수 있으므로 음수가 나온 이후의 양수들은 다 빼기로 계산

코드

#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;

int main() {
	string S;
	vector <int> V;
	int i = 0, total = 0;
	bool minus = false;

	// input
	cin >> S;

	// 문자열에서 숫자 추출
	while (i < S.size()) {

		// 0으로 시작하는 숫자의 앞부분 0 제거
		int sum = 0;
		while (isdigit(S[i])) {
			sum *= 10;
			sum += S[i] - '0';
			i++;
		}

		// 추출된 숫자 저장, 이 때 음수로 구분하여 저장
		if (sum) {
			if (minus) {
				V.push_back(-sum);
				minus = false;
			}
			else V.push_back(sum);
		}

		// 부호 판단
		else {
			if (S[i] == '-') minus = true;
			i++;
		}
	}

	// 숫자 계산
	total = V[0];
	for (int i = 1; i < V.size(); i++) {

		if (minus) {
			if (V[i] > 0) total -= V[i];
			else total += V[i];
		}
		else total += V[i];

		// 한 번 음수가 나오면 그 뒤의 숫자들도 모두 음수로 계산
		if (V[i] < 0) minus = true;
	}

	printf("%d", total);
	return 0;
}

'Study > Algorithm' 카테고리의 다른 글

BOJ (C/C++) 13305번: 주유소  (0) 2023.05.01
BOJ (C/C++) 1931번: 회의실 배정  (0) 2023.05.01
BOJ (C/C++) 2211번: 네트워크 복구  (0) 2023.04.28
BOJ (C/C++) 5972번: 택배 배송  (0) 2023.04.28
BOJ (C/C++) 1719번: 택배  (0) 2023.04.28