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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

2504๋ฒˆ: ๊ด„ํ˜ธ์˜ ๊ฐ’

4๊ฐœ์˜ ๊ธฐํ˜ธ ‘(’, ‘)’, ‘[’, ‘]’๋ฅผ ์ด์šฉํ•ด์„œ ๋งŒ๋“ค์–ด์ง€๋Š” ๊ด„ํ˜ธ์—ด ์ค‘์—์„œ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ์—ด์ด๋ž€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ •์˜๋œ๋‹ค. ํ•œ ์Œ์˜ ๊ด„ํ˜ธ๋กœ๋งŒ ์ด๋ฃจ์–ด์ง„ ‘()’์™€ ‘[]’๋Š” ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ์—ด์ด๋‹ค.  ๋งŒ์ผ

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ์ธ์ง€ ํŒ๋‹จํ•˜๋ฉด์„œ, `()`์ธ ๊ฒฝ์šฐ์—๋Š” 2๋กœ ์น˜ํ™˜ํ•˜๊ณ  `[]`์ธ ๊ฒฝ์šฐ์—๋Š” 3์œผ๋กœ ์น˜ํ™˜ํ•˜์—ฌ ๊ณ„์‚ฐํ•˜๋Š” ๊ณผ์ •์ด ํ•„์š”ํ•˜๋‹ค. ๋˜ํ•œ ์น˜ํ™˜๋œ ๊ฐ’์ด `()` ๋˜๋Š” `[]` ์‚ฌ์ด์— ์žˆ๋‹ค๋ฉด 2๋‚˜ 3์ด ๊ณฑํ•ด์ง€๊ฒŒ ๋œ๋‹ค. ์ฒ˜์Œ์—๋Š” ํ•ด๋‹น ๊ณผ์ •์„ ํ•˜๋‚˜๋กœ ์ฒ˜๋ฆฌํ•˜๋ ค๊ณ  ํ–ˆ๋Š”๋ฐ, ์ฝ”๋“œ ์ฝ๊ธฐ๊ฐ€ ํž˜๋“ค์–ด ๋”ฐ๋กœ ํŒ๋‹จํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋‹ค.

 

  • ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„ ๊ด„ํ˜ธ๋“ค์ด ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ์ธ์ง€ ํŒ๋‹จํ•œ๋‹ค.
  • ๊ฐ ๊ด„ํ˜ธ๋“ค์„ ๊ณ„์‚ฐํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.
    • stack์— `()`์™€ `[]`๊ฐ€ ๋งŒ๋‚  ๊ฒฝ์šฐ ๋ณ€ํ™˜๋˜๋Š” ์ˆซ์ž๋ฅผ ๋ฐ˜์˜ํ•œ๋‹ค.
    • ์ˆซ์ž์™€ ๊ด„ํ˜ธ๊ฐ€ ๋งŒ๋‚˜๋Š” ์ƒํ™ฉ์„ ๊ณ ๋ คํ•˜์—ฌ, sub total์„ ํ†ตํ•ด ๊ฐ’์„ ๋ฐ˜์˜ํ•˜์—ฌ stack์— ๋„ฃ๋Š”๋‹ค.
    • ๋ชจ๋“  ์ž…๋ ฅ ๊ฐ’์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๊ฐ€ ๋๋‚œ ํ›„, ํ•ฉ์„ ๊ณ„์‚ฐํ•œ๋‹ค.
  • ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ํ™œ์šฉํ•˜์—ฌ, ๊ฐ€๋…์„ฑ์„ ๋†’์ด๊ณ ์ž ํ–ˆ๋Š”๋ฐ ๋†’์•„์ง„์ง€๋Š” ๋ชจ๋ฅด๊ฒ ๋‹ค.

 

์ฝ”๋“œ

from sys import stdin

case = {
    '(': ')',
    '[': ']'
}


def possible() -> bool:
    stack = []

    for bracket in string:
        if bracket in case.keys():
            stack.append(bracket)
        elif bracket in case.values():
            if stack and bracket == case[stack[-1]]:
                stack.pop()
            else:
                return False

    return True if not stack else False


def change_bracket(value) -> None:
    cur_stack, cur_bracket = value
    sub_total = 0
    num = 2 if cur_bracket == ')' else 3

    while cur_stack:
        top = cur_stack.pop()
        if type(top) == str and cur_bracket == case[top]:
            cur_num = num if not sub_total else num * sub_total
            cur_stack.append(cur_num)
            break

        sub_total += top


def calculate() -> int:
    stack = []

    for bracket in string:
        if bracket in case.keys():
            stack.append(bracket)
        elif stack and bracket in case.values():
            change_bracket([stack, bracket])

    return sum(stack)


if __name__ == '__main__':
    string = stdin.readline().strip()
    print(calculate() if possible() else 0)

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€