์๊ณ ๋ฆฌ์ฆ ๐ก
6. ์๊ธ์ค(ํ)_ํ์ด์ฌ
@ENFJ
2025. 2. 17. 17:06
import sys
from collections import deque
# ์
๋ ฅ๊ฐ: 5 2
#60 50 70 80 90
sys.stdin=open("C:\\input.txt",'rt')
n, m = map(int,input().split())
Q = [(pos,val)for pos,val in enumerate(list(map(int,input().split())))]
Q = deque(Q)
print(Q)
cnt = 0
while True:
cur = Q.popleft()
if any(cur[1] < x[1] for x in Q):
Q.append(cur)
else:
cnt +=1
if cur[0] == m:
print(cnt)
break
๐ ๋ฌธ์ ์ค๋ช
- ํ์ N๋ช ์ด ๋๊ธฐ์ค์ ์์.
- ๊ฐ ํ์์ ์ํ๋(์ฐ์ ์์)๊ฐ ์ฃผ์ด์ง.
- ์ํ๋๊ฐ ๋์ ํ์๋ถํฐ ์ง๋ฃ๋จ.
- M๋ฒ์งธ ํ์๊ฐ ๋ช ๋ฒ์งธ๋ก ์ง๋ฃ๋ฐ๋์ง ์ถ๋ ฅํด์ผ ํจ.
๐ ์คํ ์์
์ ๋ ฅ
5 2
60 50 70 80 90
(ํ์ 5๋ช , 2๋ฒ ํ์๊ฐ ๋ช ๋ฒ์งธ๋ก ์ง๋ฃ๋ฐ๋์ง ์ฐพ๊ธฐ)
ํ์ ์ํ ๋ณํ
๋จ๊ณ๋๊ธฐ์ด (Q)์ง๋ฃ๋ฐ์ ํ์
์ด๊ธฐ | [(0,60), (1,50), (2,70), (3,80), (4,90)] | - |
1 | [(2,70), (3,80), (4,90), (0,60), (1,50)] | - |
2 | [(3,80), (4,90), (0,60), (1,50), (2,70)] | - |
3 | [(4,90), (0,60), (1,50), (2,70), (3,80)] | - |
4 | [(0,60), (1,50), (2,70), (3,80)] | 90 |
5 | [(1,50), (2,70), (3,80), (0,60)] | 80 |
6 | [(1,50), (3,80), (0,60)] | 70 (2๋ฒ ํ์) |
์ถ๋ ฅ ๊ฒฐ๊ณผ
3
โก 2๋ฒ ํ์๋ 3๋ฒ์งธ๋ก ์ง๋ฃ๋ฐ์! โ
๐ ์ต์ ํ ์ฝ๋
๐ก max()๋ฅผ ์ฌ์ฉํด์ any() ์ฐ์ฐ์ ์ต์ ํํ ์ ์์ด!
from collections import deque
n, m = map(int, input().split())
Q = deque(enumerate(map(int, input().split()))) # (ํ์ ๋ฒํธ, ์ํ๋) ์ ์ฅ
cnt = 0
while True:
cur = Q.popleft()
# ์ค์๋๊ฐ ๊ฐ์ฅ ๋์ ํ์๊ฐ ์๋์ง ํ์ธ
if cur[1] < max(Q, key=lambda x: x[1])[1]:
Q.append(cur) # ์ํ๋๊ฐ ๋ฎ์ผ๋ฉด ๋ค์ ํ์ ์ฝ์
else:
cnt += 1 # ์ง๋ฃ๋ฐ์
if cur[0] == m:
print(cnt)
break
- max(Q, key=lambda x: x[1]) ์ฌ์ฉ → any()๋ณด๋ค ํจ์จ์
- O(n²) → O(n log n)๋ก ์ต์ ํ ๊ฐ๋ฅ
โ ์ ๋ฆฌ
โ
์๊ธ์ค ๋ฌธ์ (์ฐ์ ์์ ํ ํ์ฉ) ํด๊ฒฐ!
โ
Deque ํ์ฉ → popleft() ์ฐ์ฐ ์ต์ ํ
โ
any() ๋์ max()๋ก ์ต์ ํ ๊ฐ๋ฅ
โ
์๊ฐ ๋ณต์ก๋ O(n²) → O(n log n)์ผ๋ก ๊ฐ์ ๊ฐ๋ฅ