๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/๋ฐฑ์ค€(BOJ)

[ ํŒŒ์ด์ฌ(python) ] ๋ฐฑ์ค€ 1874 - ์Šคํƒ ์ˆ˜์—ด

by YWTechIT 2021. 6. 30.
728x90

๐Ÿ“ ๋ฐฑ์ค€ 1874 - ์Šคํƒ ์ˆ˜์—ด

๋ฌธ์ œ: ๋ฐฑ์ค€ 1874 - ์Šคํƒ ์ˆ˜์—ด


๐Ÿ’ก ๋‚˜์˜ ํ’€์ด

๋‚˜์—๊ฒ ๋‚œ์ด๋„๊ฐ€ ์žˆ๋˜ ๋ฌธ์ œ์˜€๋‹ค. ๋ฌธ์ œ์˜ ๊ธธ์ด๋Š” ์งง์•˜์ง€๋งŒ ์ดํ•ดํ•˜๊ธฐ๊นŒ์ง€ ์‹œ๊ฐ„์ด ์˜ค๋ž˜ ๊ฑธ๋ ธ๋‹ค.

 

์ค‘์š”ํ•œ ํฌ์ธํŠธ๋Š” ์Šคํƒ์— pushํ•˜๋Š” ์ˆœ์„œ๋Š” ๋ฐ˜๋“œ์‹œ ์˜ค๋ฆ„์ฐจ์ˆœ์„ ์œ ์ง€ํ•œ๋‹ค.๋ผ๋Š” ๋ฌธ์žฅ์ธ๋ฐ, ์ด๋ฅผ ๋‹ค์‹œ ๋งํ•˜๋ฉด push ์ˆœ์„œ๋Š” ํ˜„์žฌ ๋งŒ๋“ค์–ด์•ผ ํ•  ์ˆ˜์—ด๋ณด๋‹ค ์ž‘์•„์งˆ ์ˆ˜ ์—†๊ณ  ์˜ค์ง current = target ํ˜น์€ current > target ํ• ๋•Œ๋งŒ ์„ฑ๋ฆฝํ•œ๋‹ค๋Š” ์˜๋ฏธ๋‹ค. ์ด๋ฅผ ์ดํ•ดํ•˜๊ธฐ๊นŒ์ง€๋Š” ๊ฝค ์˜ค๋žœ ์‹œ๊ฐ„์ด ๊ฑธ๋ ธ๋‹ค. 

 

๋˜, current๋Š” ์–ด๋–ป๊ฒŒ ๊ตฌํ˜„ํ•ด์•ผํ•˜์ง€๋ฅผ ๊ณ ๋ฏผํ–ˆ๋Š”๋ฐ 1~n๊นŒ์ง€ ์„ ์–ธํ•œ ๋‹ค์Œ ์—ฌ๊ธฐ์„œ ๋ฝ‘์ง€ ์•Š์€ ๊ฐ’ ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’๋“ค์„ ๊ฐ€์ ธ์™€์•ผ ํ•˜๋Š” ๊ฑด๊ฐ€? ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ๊ฒฐ๋ก ์ ์œผ๋กœ current += 1์”ฉ ์ฆ๊ฐ€ํ•˜๋ฉด์„œ ๊ฐ’์„ ๋„ฃ์œผ๋ฉด ๋œ๋‹ค.

 

  1. current๊ฐ€ target๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์„ ๋•Œ ๊นŒ์ง€ current๋ฅผ stack์— ๋„ฃ์–ด์ค€๋‹ค. (push ์—ฐ์‚ฐ)
  2. ๋งŒ์•ฝ, stack[-1]์ด target๊ณผ ๊ฐ™๋‹ค๋ฉด pop ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ•œ๋‹ค.
  3. ์—ฐ์‚ฐ์ด ๋๋‚ฌ์„ ๋•Œ stack์— ์•„๋ฌด๊ฒƒ๋„ ๋‚จ์•„์žˆ์ง€ ์•Š๋‹ค๋ฉด push, pop ์—ฐ์‚ฐ์„ ์ถœ๋ ฅํ•œ๋‹ค.
  4. ์—ฐ์‚ฐ์ด ๋๋‚ฌ๋Š”๋ฐ๋„ stack์ด ๋‚จ์•„์žˆ๊ฑฐ๋‚˜ current > target์ด๋ฉด NO๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

 

# ๋‚˜์˜ ํ’€์ด
import sys
input = sys.stdin.readline

n = int(input())
targets = [int(input()) for _ in range(n)]

flag = True
stack, answer, current = [], [], 0

for target in targets:
    while True:
        if stack and stack[-1] == target:    # stack: ์„ ์ž‘์„ฑํ•œ ์ด์œ ๋Š” ๋งจ ์ฒ˜์Œ stack์€ ์•„๋ฌด๊ฒƒ๋„ ์—†๊ธฐ ๋•Œ๋ฌธ
            answer.append('-')
            stack.pop()
            break

        elif current > target:
            flag = False

        else:
            current += 1
            stack.append(current)
            answer.append('+')

        if not flag:
            print('NO')
            exit()

if flag:
    print('\n'.join(answer))
# ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด
import sys
input = sys.stdin.readline

n = int(input())
targets = [int(input()) for _ in range(n)]
current = 1
stack, answer = [], []

for target in targets:
    while current <= target:
        stack.append(current)
        answer.append('+')
        current += 1

    if stack[-1] == target:
        answer.append('-')
        stack.pop()

if not stack:
    print('\n'.join(answer))
else:
    print('No')
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€