백준 #1541 잃어버린 괄호

2022. 7. 29. 16:53코딩 공부 연습

반응형

이거는 어려운 문제가 아닌데 너무 이상하게 푼 것 같아 마음이 좀 아리다...  시간도 오래 걸리고 더 좋은 방법이 있었을 것 같은데 떠오르지 않았다.

 괄호를 쳐서 가장 작은 값을 얻어야 하는데, 난 처음에 -가 나온다면 이후의 모든 + 부호를 -로 바꾸어주고 그 식을 계산만 하면 가장 작은 값을 구할 수 있을 것이라 생각했다. 예를 들어 1 - 2 + 3+ 4 + 5 - 1 + 2 + 3 이 있으면,  1 - (2 + 3+ 4 + 5) - (1 + 2 + 3) 이런 식으로 묶어주면 당연히 가장 작은 수 일텐데, 이게 곧 - 뒤에나오는 모든 + 기호를 -로 바꿔주는 것이랑 같은 말이기 때문이다. - 가 나오기 전의 +부호는 유지해주며 우선 한번 스트링 배열을 순회하며 + 들을 - 로 바꿔주었다. 이후 처음부터 다시 배열을 순회하며 정수로 바꾸어 부호에 맞게 계산을 해준게 다다!! while 문을 두번 돌려서 시간이 좀 걸렸겠지만 배열길이가 50을 안넘기 때문에 괜찮다!!

헤헤

 

#include<iostream>
#include<string>
#include <map>
#include<set>
#include<stack>
#include<queue>
#include <vector>
#include <functional>
#include <algorithm>
#include<cmath>
#include <cstring>
#include <set>
#include <stdio.h>

using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    string input;
    int i;
    long long tmp = 0;
    long long ans = 0;
    int flag_minus = 0;
    cin>>input;
    i = 0;
    
    while (input[i])
    {
        if (input[i] == '-')
        {
            flag_minus = 1;
        }
        else if (input[i] == '+')
        {
           if (flag_minus == 1)
           {
               input[i] = '-';
           }
        }
        i++;
    }
    i = 0;
    int prev_booho = 0; //0이 +, 1이 -
    while (input[i])
    {
        if (input[i] == '-')
        {
            if(prev_booho == 1)
                ans -= tmp;
            else
                ans += tmp;
            tmp = 0;
            prev_booho = 1;
        }
        else if (input[i] == '+')
        {
            if(prev_booho == 1)
                ans -= tmp;
            else
                ans += tmp;
            tmp = 0;
            prev_booho = 0;
        }
        else
        {
            tmp *=10;
            tmp += input[i] - '0';
        }
        i++;
    }
    if(prev_booho == 1)
        ans -= tmp;
    else
        ans += tmp;
    cout<<ans;
    return (0);
}