์•Œ๊ณ ๋ฆฌ์ฆ˜ ๐Ÿ’ก

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)์œผ๋กœ ๊ฐœ์„  ๊ฐ€๋Šฅ