어제의 나보다 성장한 오늘의 나

[c++][Greedy] 백준 1541번 문제 풀이 본문

c++/백준 문제 풀이

[c++][Greedy] 백준 1541번 문제 풀이

today_me 2022. 2. 19. 22:43
반응형

풀이 :

 

① 입력 된 문장을 +,- 와 숫자로 나눈다. ( substr 사용)

② 조건에 맞게 계산을 한다.

가장 작은 값이 결과로 나오도록 해야 하므로 - 가 나오기 전까지는 모든 숫자를 더 해주고,

-가 한 번이라도 나오면 그 이후로는 모두 빼주면 된다.

 

 

Coding

 

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int args ,char** argv){

    string str;
    cin >> str;

    vector<char> ops; // str에 들어있는 + , - 순서대로 저장.
    vector<int> nums; // str에 들어있는 숫자들 순서대로 저장.

    int first_index = 0;
    int last_index = 0;

    // 입력된 문장을 + , - 와 숫자들로 분류. substr 사용.

    for(int i = 0 ; i < str.size() ; ++i){

        if(str[i] == '+'){
            nums.push_back(stoi(str.substr(first_index , last_index - first_index)));
            ops.push_back(str[i]);
            first_index = i + 1;
            last_index++;
        }
        else if(str[i] == '-'){
            nums.push_back(stoi( str.substr(first_index , last_index - first_index)));
            ops.push_back(str[i]);
            first_index = i + 1;
            last_index++;
        }
        else if(i==str.size() - 1){
            nums.push_back(stoi(str.substr(first_index , last_index + 1 - first_index)));
        }
        else{
            last_index++;
        }
    }

        int total = nums[0];
        
        for(int i = 0 ; i < ops.size() ; ++i){
            
            if(ops[i]=='-'){
                for(int j = i + 1 ; j < nums.size() ; ++j){
                    total -= nums[j];
                }
                break;
            }

            else if(ops[i]=='+'){
                total += nums[i+1];
            }

        }
    cout << total;
}

 

 

substr에 대하여 자세히 알고 싶다면 아래 글을 참조 하자.

2022.02.19 - [c++/문법] - [c++] 문자열 자르기 / 쪼개기 (Substr , Sstream , Strtok) 총정리 및 예제

 

[c++] 문자열 자르기 / 쪼개기 (Substr , Sstream , Strtok) 총정리 및 예제

1) s.substr(시작 위치 , 문자열의 길이) string s = "0123456789"; string subs1 = s.substr(2,5); // subs1 = "23456" string s = "0123456789"; string subs1 = s.substr(5); // subs1 = "56789" string s = "0..

8156217.tistory.com

 

 

백준 1541번 문제

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

 

1541번: 잃어버린 괄호

첫째 줄에 식이 주어진다. 식은 ‘0’~‘9’, ‘+’, 그리고 ‘-’만으로 이루어져 있고, 가장 처음과 마지막 문자는 숫자이다. 그리고 연속해서 두 개 이상의 연산자가 나타나지 않고, 5자리보다

www.acmicpc.net

 

반응형
Comments