알고리즘/백준

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

녕이 2022. 7. 13. 10:29
728x90

 

 

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

 

1541번: 잃어버린 괄호

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

www.acmicpc.net

 

최대한 숫자를 - 해야 한다.

- 뒤에 괄호를 씌우면 괄호 안에 있는 숫자들이 모두 -가 된다.

그러므로 - 가 하나라도 나타나면 뒤에 나오는 숫자들을 모두 음수로 만들면 된다.

 

#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace std;

int main(){
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    string s;
    int ans = 0;
    vector<int> v;
    vector<int> op;
    vector<char> op2;
    cin >> s;
    
    string tmp = "";
    bool isMinus = false;
    
    for(int i=0; i<s.size(); i++){
        if(isdigit(s[i])){
            tmp += s[i];
        }else{
            op.push_back(stoi(tmp));
            tmp = "";
            op2.push_back(s[i]);
        }
    }
    op.push_back(stoi(tmp));
    
    ans = op[0];
    for(int i=0; i<op2.size(); i++){
        if(op2[i] == '-'){
            isMinus = true;
            ans -= op[i+1];
        }
        if(op2[i] == '+'){
            if(!isMinus) ans += op[i+1];
            else         ans -= op[i+1];
        }
    }
    cout << ans << '\n';
    return 0;
}

 

 

 

 

 

728x90