Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1541: 잃어버린 괄호 #6

Open
minsoo0715 opened this issue Sep 3, 2023 · 0 comments
Open

1541: 잃어버린 괄호 #6

minsoo0715 opened this issue Sep 3, 2023 · 0 comments
Assignees
Labels
#그리디 그리디 문제 #문자열 문자열 문제 @백준 백준(https://www.acmicpc.net) 문제 C/C++ c/c++로 해결한 문제들

Comments

@minsoo0715
Copy link
Owner

minsoo0715 commented Sep 3, 2023

1541: 잃어버린 괄호

소스 코드

아이디어

마이너스를 만나면 다음 마이너스를 만날 때까지 괄호를 씌워 덧셈 값을 뺄셈 값으로 바꾸게 함

ex. 40-30+40-20+40 -> 40-(30+40)-(20+40) -> 최소

구현

편의상 뺄셈은 양수와 음수의 합으로 보고, 다음 음수를 만날 때까지 양수를 음수로 바꿈
예시: 40-30+40 -> 40+(-30) + (-40)

string str;
int chk = 0; // 이전 부호의 위치를 저장하고 있음.
int sum = 0;
bool ck = false; // 음수를 만났는지를 체크

for(int i = 0; i<str.length(); ++i) {
    if(str[i] == '-' || str[i] == '+') { // 부호를 만나면 이전 번호 추출
        int num = stoi(str.substr(chk, i));

        if(num < 0) { // 음수를 만나면 ck = true로 set
            ck = true;
        }else if(ck) { // 음수를 만났으면 양수를 음수로 만듦.
            num = -num;
        }
        sum += num; // 가산
        chk = i; // 부호 위치 갱신
    }
}
@minsoo0715 minsoo0715 added @백준 백준(https://www.acmicpc.net) 문제 C/C++ c/c++로 해결한 문제들 #그리디 그리디 문제 #문자열 문자열 문제 labels Sep 3, 2023
@minsoo0715 minsoo0715 self-assigned this Sep 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
#그리디 그리디 문제 #문자열 문자열 문제 @백준 백준(https://www.acmicpc.net) 문제 C/C++ c/c++로 해결한 문제들
Projects
None yet
Development

No branches or pull requests

1 participant