boj 1541 잃어버린 괄호 c++

 

 

문제에서 주어진 문자열에 대해 가장 작은 값을 구하려면 -가 시작되었을 때 뒤에 따라나오는 수가 가장 크면 된다.

예를 들어 10 - 30 + 50 + 100 에 대해 가장 작은 값은 - 뒤에 따라나오는 30 + 50 + 100 을 모두 더한 것이다.

즉, - 뒤의 모든 +를 더한 뒤에 전체 값에서 빼버리면 가장 작은 값이 나온다.

이것을 문장이 끝날 때까지 반복하면 끝.

 

정답 소스를 공개한다.

# include <bits/stdc++.h>
using namespace std;

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

    string line;
    int ans = 0;

    cin >> line;
    string first_number = "";
    int i = 0;
    while(isdigit(line[i]))
        first_number += line[i++];
    ans += stoi(first_number); // 첫 번째 숫자를 구함.

    while (line[i])
    {
        if (line[i] == '-')
        {
            i++;
            int t = 0;
            while (isdigit(line[i]) || line[i] == '+')
            {
                if (line[i] == '+')
                {
                    ans -= t;
                    t = 0;
                }
                else
                {
                    t = (t * 10) + (line[i] - '0') % 10; 
                  // 어떤 문자열을 숫자로 바꾸는 대표적인 코드.
                }
                i++;
            }
            ans -= t;
        }
        else
        {
            int t = 0;
            i++;
            while (isdigit(line[i]))
            {
                t = t * 10 + (line[i] - '0') % 10;
                i++;
            }
            ans += t;
        }
    }
    cout << ans;
}

 

 

백준 1541 잃어버린 괄호 cpp

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기
// custom