1541번 : 잃어버린 괄호 - Python

Pobi·2023년 4월 3일
0

PS

목록 보기
56/107

문제

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

풀이

-를 기준으로 - 뒤에 +가 나오면 먼저 한다.(다른 -가 나오거나, 끝날때 까지) -뒤에 -가 나오면 앞에 있는 -를 먼저 한다. 마친 후 남은 연산을 한다.

코드

from sys import stdin

input = stdin.readline

s = input()
s_n = list(map(int,s.replace('+','-').split('-')))
count = 0 #몇번째 연산자 까지 읽었는지 계산
o = -1
m = 0 #-의 개수를 저장

for i in range(len(s)):
    if s[i] =='+' or s[i] == '-':
        count += 1
    if s[i] == '-':
        m+=1
        if o != -1:
            n1 = s_n.pop(o-1)
            n2 = s_n.pop(o-1)
            n = n1 - n2
            s_n.insert(o-1,n)
            count -= 1
            m-=1
        o = count
    if s[i] == '+' and o!=-1: #지금 +인데, 앞에 -가 있다면
        n1 = s_n.pop(o)
        n2 = s_n.pop(o)
        n = n1 + n2
        count -= 1 #연산을 했으니 남은 연산자가 하나 줄었다.
        s_n.insert(o,n)
    

if m: #-가 남아있을 경우 계산해준다.
    n1 = s_n.pop(o-1)
    n2 = s_n.pop(o-1)
    n = n1 - n2
    count -= 1
    s_n.insert(o-1,n)

sum = 0#계산이 끝나고 나머지 들은 +들일 것이다. 다 더한다.
for i in s_n:
    sum+=i

print(sum)

반례

1-2-3+4 / -8
1000 / 1000
1-1-1 / -1
1+2-3+4+5 / -9
1-1 / 0
1+2-3+4+5 / -9
10-10+10-10+10 / -30
50-60+60+70+70-50 / -260
1+2+3+7+8 / 21
00000-1+00000-00005 / -6

profile
꿈 많은 개발자

0개의 댓글