์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ฐฑ์ค€ 2164(์นด๋“œ๋ถ„๋ฅ˜2) ๋ฌธ์ œํ’€์ด

ghtis1798 2021. 3. 12. 12:13

๐Ÿ“Œ๋ฌธ์ œ ์„ค๋ช…

๋ฐฑ์ค€ ๋ฌธ์ œํ’€์ด
๋ฐฑ์ค€ 2164 ์นด๋“œ๋ถ„๋ฅ˜2 ๋ฌธ์ œ
์ž…์ถœ๋ ฅ ๊ฒฐ๊ณผ

๐Ÿ“Œ๋ฌธ์ œ ์ ‘๊ทผ ๋ฐฉ์‹

์ฒซ ๋ฒˆ์งธ ์‹œ๋„

์•„๋ฌด์ƒ๊ฐ ์—†์ด ์‹œ๋„ํ–ˆ๋‹ค๊ฐ€ ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋–ด๋‹ค.

๋ฌธ์ œ๋ฅผ ์ ‘๊ทผํ•œ ๋ฐฉ์‹์€ ๋‹ค์Œ๊ณผ ๊ฐ™์•˜๋‹ค.

1. ์ฒซ ๋ฒˆ์งธ ์นด๋“œ๋ฅผ ์ œ๊ฑฐํ•œ๋‹ค.

2. ๋‘ ๋ฒˆ์งธ ์นด๋“œ๋ฅผ ๋งจ ๋’ค๋กœ ๋ณด๋‚ธ๋‹ค.

์œ„ ๋‘ ๊ณผ์ •์„ 1์žฅ์ด ๋‚จ์„๋•Œ๊นŒ์ง€ ์ˆ˜ํ–‰ํ•˜๋ฉด ๋˜๋Š” ๋ฌธ์ œ๋ผ๊ณ  ์ƒ๊ฐํ–ˆ๋‹ค.

๋”ฐ๋ผ์„œ ๋ฆฌ์ŠคํŠธ๋ฅผ ์‚ฌ์šฉํ–ˆ๊ณ  ๋งจ ์•ž์— ์นด๋“œ๋ฅผ ์‚ญ์ œํ•˜๊ณ  ๋’ค๋กœ ๋ณด๋‚ด๋„๋ก ๊ตฌํ˜„ํ–ˆ๋‹ค.

๋ฌธ์ œ๊ฐ€ ์—†์„๊ฑฐ๋ผ ์ƒ๊ฐํ–ˆ๋˜ ์ด์œ  ๋‘ ๊ฐ€์ง€์ด๋‹ค.

1. 1์ค‘ for๋ฌธ์„ ์‚ฌ์šฉํ–ˆ๋‹ค.

2. ์ตœ๋Œ€ ๊ฐ€๋“œ ์ˆ˜๊ฐ€ 50๋งŒ์žฅ์ด๋‹ค.

์†Œ์Šค์ฝ”๋“œ

# 2์ดˆ ์ดˆ๊ณผ - N 500000์œผ๋กœ ๋Œ€์ž… ์‹œ 79์ดˆ๊ฐ€ ๊ฑธ๋ ธ๋‹ค.
# ๋ณ‘๋ชฉ ์ง€์ ์€ ์–ด๋””์ง€?

import sys

n = int(sys.stdin.readline().rstrip())
cards = [x for x in range(1,n+1)]

def solution(cards):
    while len(cards) > 1:
        cards.pop(0)
        cards.append(cards.pop(0))
    print(cards[0])

solution(cards)

๊ฐ„๊ณผํ–ˆ๋˜ ๋ถ€๋ถ„

ํ•ด๋‹น ๋กœ์ง์ด Queue์ฒ˜๋Ÿผ ๋™์ž‘ํ•œ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๊ณ ๋„ ๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„ํ–ˆ๋‹ค.

๋”ฐ๋ผ์„œ ๊ฐ’์„ ๋„ฃ๊ณ  ๋นผ๋Š” ๊ณผ์ •์—์„œ ๊ต‰์žฅํ•œ ์„ฑ๋Šฅ ์ €ํ•˜๊ฐ€ ์ผ์–ด๋‚ฌ๋‹ค.

๋ฆฌ์ŠคํŠธ์™€ ํ์˜ ์„ฑ๋Šฅ์ฐจ์ด๊ฐ€ ๋‚˜๋Š” ์ด์œ ์— ๋Œ€ํ•ด ๋” ๊นŠ๊ฒŒ ๊ณต๋ถ€ํ•ด ๋ณผ ํ•„์š”์„ฑ์„ ๋Š๊ผˆ๋‹ค.

๐Ÿ“Œ๋ฌธ์ œ ํ’€์ด

๋‹ค์‹œ ํ๋กœ ๊ตฌํ˜„ํ•˜๋‹ˆ ๋งค์šฐ ์ž˜ ๋™์ž‘ํ–ˆ๋‹ค.

import sys
from collections import deque

n = int(sys.stdin.readline().rstrip())
cards = [x for x in range(1,n+1)]
cards = deque(cards)

def solution(cards):
    while len(cards) > 1:
        cards.popleft()
        cards.append(cards.popleft())
    print(cards[0])

solution(cards)

 

๐Ÿ“Œ์„ฑ๋Šฅ ์ฐจ์ด

2021-03-12

๋ฆฌ์ŠคํŠธ๋กœ ํ๋ฅผ ๊ตฌํ˜„ ์‹œ ์„ฑ๋Šฅ ์ฐจ์ด๊ฐ€ ๋‚˜๋Š” ์ด์œ ์— ๋Œ€ํ•ด ์ถ”๊ฐ€์ ์œผ๋กœ ๊ณต๋ถ€ํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค.

Queue

ํ๋Š” ์˜ํ™”๊ด€ ๋งคํ‘œ์†Œ์— ์ค„์„ ์„œ๋Š” ๊ตฌ์กฐ์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

๋จผ์ € ์ค„์„ ์„  ์‚ฌ๋žŒ์ด ์šฐ์„ ์ ์œผ๋กœ ํ‘œ๋ฅผ ์‚ด ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์ด์ฃ .

์ƒˆ๋กœ์šด ์‚ฌ๋žŒ์ด ๋“ค์–ด์˜ค๋ฉด ๋งจ ๋’ค์— ์ค„์„ ์„œ์•ผ ํ•ฉ๋‹ˆ๋‹ค.

์ด๊ฒƒ์„ ํŒŒ์ด์ฌ์—์„œ๋Š” ๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

list ํ•จ์ˆ˜์˜ append()์™€ pop(0)๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํ์ฒ˜๋Ÿผ ๋™์ž‘ํ•˜๋„๋ก ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

List ๋‹จ์ 

ํ•˜์ง€๋งŒ ํŒŒ์ด์ฌ์—์„œ๋Š” Queue ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ๋”ฐ๋กœ ์ œ๊ณต์„ ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

๋˜ํ•œ collections ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์•ˆ์— deque ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.

์ด์œ ๊ฐ€ ๋ฌด์—‡์ผ๊นŒ์š”?

List์˜ ๊ฒฝ์šฐ ๋งจ ๋’ค์—์„œ appendํ•˜๊ณ  popํ•  ๋•Œ๋Š” ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ O(1)์ด ๋“ญ๋‹ˆ๋‹ค.

ํ•˜์ง€๋งŒ ๋งจ ์•ž์—์„œ ๋„ฃ๊ณ  ๋นผ๊ณ  ํ•  ๊ฒฝ์šฐ O(N)์œผ๋กœ ์ฆ๊ฐ€ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

๊ทธ ์ด์œ ๋Š” ํ•˜๋‚˜๋ฅผ ์ œ๊ฑฐํ•  ๊ฒฝ์šฐ ๋น„์–ด์žˆ๋Š” ๋งŒํผ ์ด๋™์„ ์‹œ์ผœ์ค˜์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

Deque

Deque์˜ ๊ฒฝ์šฐ append() ํ•จ์ˆ˜์™€ popleft() ํ•จ์ˆ˜๋กœ ์‚ฌ์šฉํ•˜์—ฌ ํ์ฒ˜๋Ÿผ ๋™์ž‘ํ•˜๊ฒŒ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.