[BOJ][๐ŸŸก4][๋ฐฑ์ค€#17298] ์˜คํฐ์ˆ˜

์ž‘์„ฑ:    

์—…๋ฐ์ดํŠธ:

์นดํ…Œ๊ณ ๋ฆฌ:

ํƒœ๊ทธ: , , ,

๋ฌธ์ œ ์ถœ์ฒ˜

BAEKJOON Online Judge #17298


๋ฌธ์ œ

ํฌ๊ธฐ๊ฐ€ N์ธ ์ˆ˜์—ด A = A1, A2, โ€ฆ, AN์ด ์žˆ๋‹ค. ์ˆ˜์—ด์˜ ๊ฐ ์›์†Œ Ai์— ๋Œ€ํ•ด์„œ ์˜คํฐ์ˆ˜ NGE(i)๋ฅผ ๊ตฌํ•˜๋ ค๊ณ  ํ•œ๋‹ค. Ai์˜ ์˜คํฐ์ˆ˜๋Š” ์˜ค๋ฅธ์ชฝ์— ์žˆ์œผ๋ฉด์„œ Ai๋ณด๋‹ค ํฐ ์ˆ˜ ์ค‘์—์„œ ๊ฐ€์žฅ ์™ผ์ชฝ์— ์žˆ๋Š” ์ˆ˜๋ฅผ ์˜๋ฏธํ•œ๋‹ค. ๊ทธ๋Ÿฌํ•œ ์ˆ˜๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ์— ์˜คํฐ์ˆ˜๋Š” -1์ด๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, A = [3, 5, 2, 7]์ธ ๊ฒฝ์šฐ NGE(1) = 5, NGE(2) = 7, NGE(3) = 7, NGE(4) = -1์ด๋‹ค. A = [9, 5, 4, 8]์ธ ๊ฒฝ์šฐ์—๋Š” NGE(1) = -1, NGE(2) = 8, NGE(3)ย = 8, NGE(4) = -1์ด๋‹ค.


์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ์ˆ˜์—ด A์˜ ํฌ๊ธฐ N (1 โ‰ค N โ‰ค 1,000,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„์— ์ˆ˜์—ด A์˜ ์›์†Œ A1, A2, โ€ฆ, ANย (1 โ‰ค Ai โ‰ค 1,000,000)์ดย ์ฃผ์–ด์ง„๋‹ค.


์ถœ๋ ฅ

์ด N๊ฐœ์˜ ์ˆ˜ NGE(1), NGE(2), โ€ฆ, NGE(N)์„ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด ์ถœ๋ ฅํ•œ๋‹ค.


์˜ˆ์ œ

์˜ˆ์ œ 1

์ž…๋ ฅ

4
3 5 2 7


์ถœ๋ ฅ

5 7 7 -1


์˜ˆ์ œ 2

์ž…๋ ฅ

4
9 5 4 8


์ถœ๋ ฅ

-1 8 8 -1


My Sol

import sys
input = sys.stdin.readline
from heapq import heappop, heappush

N = int(input())
arr = list(map(int, input().split()))

Q = []
ret = [-1]*N
for i in range(N):
    heappush(Q, [arr[i], i])
    while Q:
        val, idx = heappop(Q)
        if arr[i] > val:
            ret[idx] = arr[i]
        else:
            heappush(Q, [val, idx])
            break

print(*ret)

heap ์‚ฌ์šฉ

  1. ์ฃผ์–ด์ง„ ์ˆ˜๋“ค์„ ํ•œ ๋ฐฐ์—ด์— ์ฒ˜๋ฆฌ
  2. 0๋ถ€ํ„ฐ N-1๊นŒ์ง€์˜ i์— ๋Œ€ํ•ด ๋งค๋ฒˆ ๊ฐ’๊ณผ ์ธ๋ฑ์Šค๋ฅผ heapQ์— ์‚ฝ์ž…
  3. Q์—์„œ ํ˜„์žฌ๊นŒ์ง€ ๋ˆ„์  ์ˆ˜ ์ค‘์— ๊ฐ€์žฅ ๊ฐ’์ด ์ž‘์€ ๊ฐ’๊ณผ ํ•ด๋‹น ๊ฐ’์˜ ์ธ๋ฑ์Šค ์ถ”์ถœ
  4. arr[i]๊ฐ€ val๋ณด๋‹ค ํฌ๋‹ค๋ฉด, ์–ด๋–ค ์ธ๋ฑ์Šค์˜ ์˜คํฐ์ˆ˜๋ฅผ ์ฒ˜์Œ์œผ๋กœ ๋ฐœ๊ฒฌํ•œ ๊ฒƒ. ret[idx]์— arr[i]๋ฅผ ๋ถ€์—ฌ(์˜คํฐ์ˆ˜ ๋ถ€์—ฌ)
  5. ์ด๋ฅผ ๋ฐ˜๋ณต


๊ฒฐ๊ณผ

๋งž์•˜์Šต๋‹ˆ๋‹ค!!


๋ชจ๋ฒ”๋‹ต์•ˆ

์ถœ์ฒ˜

N = int(input())
nums = list(map(int,input().split(' ')))
out = [-1]*N

stack = [0]
for i in range(1,N):
    while stack and nums[stack[-1]] < nums[i]:
        j = stack.pop()
        out[j] = nums[i]
    stack.append(i)

print(" ".join(map(str,out)))

์—ฐ์‚ฐ์‹œ๊ฐ„์ด ๋‚˜์˜ 25% ์ •๋„์ธ ํ’€์ด๋ฅผ ๋ถ„์„ํ•ด๋ณด๋ ค ํ•œ๋‹ค.

์ด ๋ถ„์€ stack์„ ์‚ฌ์šฉํ•˜์…จ๊ณ , stack์— index๋งŒ ๋„ฃ์œผ๋ฉฐ ๋น„๊ตํ•˜์˜€๋‹ค. heapq์— ์›์†Œ์™€ ์ธ๋ฑ์Šค๋ฅผ ๋„ฃ๊ณ  ๋นผ๊ณ  ํ•  ํ•„์š”๊ฐ€ ์—†์ด stack์˜ ๋งˆ์ง€๋ง‰ ๊ฐ’๋งŒ ๋น„๊ตํ•˜์˜€์œผ๋ฏ€๋กœ ๋ถˆํ•„์š”ํ•œ ๊ณผ์ •์ด๋‚˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ถ”๊ฐ€๋กœ ์ ์žฌํ•˜์ง€ ์•Š์•„ ์—ฐ์‚ฐ์‹œ๊ฐ„์ด ์งง์•˜์„ ๊ฒƒ์ด๋‹ค.

ํ•œ ๊ฐ€์ง€ ์•„์‰ฌ์šด ๊ฑด ์ž…์ถœ๋ ฅ์— ๋Œ€ํ•ด์„œ *out์„ ํ•˜์ง€ ์•Š๊ณ  join์œผ๋กœ ํ’€์–ด๋ƒˆ๋‹ค๊ฑฐ๋‚˜ .split()์œผ๋กœ ๋ฉ”์„œ๋“œ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋ฉด .split(โ€œ โ€œ)์ฒ˜๋Ÿผ ๊ณต๋ฐฑ์„ default๋กœ ํ•œ๋‹ค๋Š” ์‚ฌ์‹ค์„ ๋ชจ๋ฅด๊ณ  ๊ณ„์‹  ๊ฒƒ ๊ฐ™๋‹ค. ๊ทธ๋Ÿฐ ๊ฒƒ์— ๋น„ํ•ด ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž์ฒด๋Š” ๋ฐœ์ƒ์ด ์ข‹์•˜๋‹ค.

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ