Post

[BOJ] 1874. ์Šคํƒ์ˆ˜์—ด(python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

๐Ÿ’ช์•„์ด๋””์–ด

  1. ์ฃผ์–ด์ง„ ์ˆ˜์—ด ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š”์ง€ ๊ฒ€์‚ฌ
    max ๊ฐ’์€ ํ•ด๋‹น ์ธ๋ฑ์Šค์˜ ์ˆ˜์—ด๊ฐ’์„ ๊ฐฑ์‹ ํ•ด ๊ฐ€๋ฉด์„œ ๊ฒ€์‚ฌํ•ด ์คฌ๋‹ค. max์˜ ์ตœ๋Œ“๊ฐ’์€ n์ด๋‹ค.
    n์— ๋„๋‹ฌํ•˜๋ฉด ๊ทธ๋‹ค์Œ๋ถ€ํ„ฐ๋Š” ์ž‘์€ ์ˆ˜๊ฐ€ ๋‚˜์˜ฌํ…Œ๋‹ˆ๊นŒ max๊ฐ’์„ stack์˜ ๋งจ ์œ„์˜ ๊ฐ’์œผ๋กœ ๊ฐฑ์‹ ํ•˜๊ฐ€๋ฉด์„œ True,False๊ฒ€์‚ฌํ•˜๋Š” ๋ฒ”์œ„๋ฅผ ์ค„์—ฌ์คฌ๋‹ค.
    • max๊ฐ’๊ณผ ๋น„๊ต
      • arr[i]>max: arr[i]-max๋งŒํผ +์ถœ๋ ฅํ•˜๊ณ  / -์ถœ๋ ฅ/ False / max=arr[i]
      • arr[i]<max: max๋ณด๋‹ค ์ž‘์€ ์ˆ˜๋“ค ์ค‘ ์ œ์ผ ๊ฐ€๊นŒ์šด True ์ฐพ๊ธฐ (j) โ€“> ์ด j๊ฐ’์ด stack[-1]
        stack[-1]๊ฐ’๊ณผ arr[i]์ด ๋‹ค๋ฅด๋ฉด stack์˜ LIFO์œผ๋กœ ์ธํ•ด ๋ชป๋งŒ๋“œ๋Š” ๋ฐฐ์—ด
        ๊ฐ™์œผ๋ฉด False๋กœ ๋ฐ”๊พธ๊ณ  -์ถœ๋ ฅ
      • if max == n: max = j : ๊ฒ€์‚ฌ ๋ฒ”์œ„ ์ค„์ด๊ธฐ

๐Ÿฅ‚์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def is_possible(arr,n):
    answer = []
    nums = [True]*(n+1)
    max_val = 0
    chk=0
    for num in arr:
        if max_val < num:
            for _ in range(max_val,num):
                answer.append('+')
            max_val = num
            nums[num] = False
            answer.append('-')
        else:
            for i in range(max_val-1,-1,-1):
                if nums[i]:
                    if i==num: 
                        answer.append('-')
                        nums[i]=False
                        if max_val==n: chk=1
                        if chk: max_val=i
                        break
                    else: return False
    return answer

arr = []
n = int(input())

for _ in range(n):
    arr.append(int(input()))

answer = is_possible(arr,n)

if answer: 
    for a in answer: print(a)
else: print('NO')
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.