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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

3015๋ฒˆ: ์˜ค์•„์‹œ์Šค ์žฌ๊ฒฐํ•ฉ

์ฒซ์งธ ์ค„์— ์ค„์—์„œ ๊ธฐ๋‹ค๋ฆฌ๊ณ  ์žˆ๋Š” ์‚ฌ๋žŒ์˜ ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ N ≤ 500,000) ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ ์‚ฌ๋žŒ์˜ ํ‚ค๊ฐ€ ๋‚˜๋…ธ๋ฏธํ„ฐ ๋‹จ์œ„๋กœ ์ฃผ์–ด์ง„๋‹ค. ๋ชจ๋“  ์‚ฌ๋žŒ์˜ ํ‚ค๋Š” 231 ๋‚˜๋…ธ๋ฏธํ„ฐ ๋ณด๋‹ค ์ž‘๋‹ค. ์‚ฌ๋žŒ๏ฟฝ๏ฟฝ

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 N๋ช…์ด ํ•œ ์ค„๋กœ ์„œ์„œ ๊ธฐ๋‹ค๋ฆฌ๊ณ  ์žˆ์„ ๋•Œ, ๋ณผ ์ˆ˜ ์žˆ๋Š” ์‚ฌ๋žŒ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ๋‘ ์‚ฌ๋žŒ A์™€ B๊ฐ€ ์„œ๋กœ ๋ณด๊ธฐ ์œ„ํ•ด์„œ๋Š” A, B ์‚ฌ์ด์— ๋‘˜ ๋ณด๋‹ค ํ‚ค๊ฐ€ ํฐ ์‚ฌ๋žŒ์ด ์—†์–ด์•ผ ํ•œ๋‹ค. ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด์„œ๋Š” `stack`์„ ํ™œ์šฉํ•˜์—ฌ, ํ˜„์žฌ `top`๋ณด๋‹ค ํฐ ํ‚ค๊ฐ€ ์ž…๋ ฅ๋œ๋‹ค๋ฉด, ์ดํ›„์— ์ž…๋ ฅ๋˜๋Š” ๊ฐ’์€ ํ˜„์žฌ์˜ `top`์„ ๋ณผ ์ˆ˜ ์—†์œผ๋ฏ€๋กœ `pop`์„ ํ•˜์—ฌ์•ผ ํ•œ๋‹ค. ์ด์™€ ๋ฐ˜๋Œ€์˜ ๊ฒฝ์šฐ ๋ผ๋ฉด `stack`์— ์ถ”๊ฐ€ํ•œ๋‹ค. ์ฃผ์˜ํ•ด์•ผ ํ•  ๊ฒƒ์€ ์—ฐ์†๋œ ๋™์ผํ•œ ์ˆซ์ž๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด stack์— ์ถ”๊ฐ€ํ•  ๋•Œ `(ํ‚ค, ์—ฐ์†๋œ ํšŸ์ˆ˜)`๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

 

์ฝ”๋“œ

from sys import stdin


def solve():
    stack = []
    answer = 0

    for h in height:
        while stack and stack[-1][HEIGHT] < h:
            answer += stack.pop()[CNT]

        if not stack:
            stack.append((h, 1))
        else:
            if stack[-1][HEIGHT] == h:
                cnt = stack.pop()[CNT]
                answer += cnt

                if stack:
                    answer += 1

                stack.append((h, cnt + 1))
            else:
                stack.append((h, 1))
                answer += 1
    return answer


if __name__ == '__main__':
    HEIGHT, CNT = 0, 1
    n = int(stdin.readline())
    height = [int(stdin.readline()) for _ in range(n)]
    print(solve())

 

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