[백준/C++] 1541번 잃어버린 괄호

TaerinLog·2025년 6월 16일

문제 링크

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

풀이

  • 식의 값을 최소로 만들어야함 > 음수를 최대로 만들어야함
    • - 기호 이후의 숫자는 모두 음수로 처리

코드

#include <iostream>
#include <algorithm> 
#include <string>

using namespace std;

int main(){
    string text; 
    cin >> text; 
    
    int start_idx = 0, end_idx = 0;
    int plag = 0;
    // 양수, 음수의 합을 저장하는 배열
    int sum[2] = {0,0};

    for(auto ch : text){
        end_idx++;
        if('+'== ch){
            sum[plag] += atoi(text.substr(start_idx, end_idx - start_idx).c_str());
            start_idx = end_idx;
        }
        // - 기호가 나오면 그 뒤의 숫자는 모두 음수로 판단
        else if('-'== ch){
            sum[plag] += atoi(text.substr(start_idx, end_idx - start_idx).c_str());
            start_idx = end_idx;
            // 첫번째 숫자는 양수이기 때문에, 
            plag = 1;
        }
    }
    // 마지막 숫자
    sum[plag] += atoi(text.substr(start_idx).c_str());

    cout << sum[0] - sum[1];
}
profile
taerin

0개의 댓글