ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90

๐Ÿšฉ stack, ํ›„์œ„ํ‘œ๊ธฐ์‹(postfix)

 

์ฝ”๋“œ

T = 10

for tc in range(1, T+1):
    N = int(input())  # ๋ฌธ์ž์—ด๊ธธ์ด
    S = input()  # input ๋ฌธ์ž์—ด

    stack = []
    postfix = ''  # ํ›„์œ„ํ‘œ๊ธฐ์‹ ๋ฌธ์ž์—ด
    cal = []  # ๊ณ„์‚ฐํ•  ์Šคํƒ

    # 1. ํ›„์œ„ํ‘œ๊ธฐ์‹์œผ๋กœ ๋ณ€ํ™˜
    for i in S:
        # ์Šคํƒ ๋น„์—ˆ์œผ๋ฉด ์—ฐ์‚ฐ์ž ๋„ฃ๊ณ 
        if not stack and i == '+':
            stack.append(i)
        # ์Šคํƒ์— ์ด๋ฏธ +๊ฐ€ ์žˆ์œผ๋ฉด ๋นผ๊ณ  ์ถ”๊ฐ€
        elif stack and i == '+':
            postfix += stack.pop()
            stack.append(i)
        # ์ˆซ์ž์ด๋ฉด ๊ทธ๋ƒฅ ์ถ”๊ฐ€
        else:
            postfix += i
    # ์Šคํƒ์— ๋‚จ์•„์žˆ๋Š” ๋งˆ์ง€๋ง‰ + ๋นผ์ค˜์•ผ๋˜์„œ for~else ๋กœ ์ฒ˜๋ฆฌํ•จ
    else:
        postfix += stack.pop()

    # 2. ๊ฒฐ๊ณผ๊ฐ’ ๊ณ„์‚ฐ
    for i in postfix:
        # ์ˆซ์ž์ด๋ฉด ์Šคํƒ์— ๋„ฃ๊ณ 
        if i != '+':
            cal.append(int(i))
        # ์—ฐ์‚ฐ์ž์ด๋ฉด ์Šคํƒ์˜ ์ˆซ์ž ๋‘๊ฐœ ๊บผ๋‚ด์„œ ๋”ํ•˜๊ณ  ๋‹ค์‹œ ๋„ฃ์Œ
        elif i == '+':
            num2 = cal.pop()
            num1 = cal.pop()
            cal.append(num1+num2)

    print("#{} {}".format(tc, *cal))
๋Œ“๊ธ€