์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ/BOJ_Python

[BOJ/Step14] 15649 : N๊ณผ M (1) (Python)

NaNaRin๐Ÿ™ƒ 2021. 2. 20. 14:44

www.acmicpc.net/problem/15649

 

15649๋ฒˆ: N๊ณผ M (1)

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

www.acmicpc.net


1 ~ N ์ค‘ ์ค‘๋ณต ์—†์ด M๊ฐœ์˜ ์ˆ˜๋ฅผ ๊ณ ๋ฅด๋Š” ๊ฒฝ์šฐ๋ฅผ ๋ชจ๋‘ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ

 

(1) ๋ฆฌ์ŠคํŠธ์— ๋ฏธ๋ฆฌ m๊ฐœ๋งŒํผ์˜ 0์„ ์ €์žฅํ•œ ํ›„ index ์ˆœ์„œ๋Œ€๋กœ ์ฑ„์›Œ๋„ฃ์œผ๋ฉฐ ์ถœ๋ ฅํ•˜๋Š” ๋ฐฉ๋ฒ•

  def sequence( seq, n, m, index ) :

    1. i๊ฐ€ 1 ~ N๊นŒ์ง€ ๋ฐ˜๋ณต

    2. ๋ฆฌ์ŠคํŠธ seq[:index]์— ๋Œ€์ž…ํ•˜๋ ค๋Š” i ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜์—ฌ ์žˆ์œผ๋ฉด continue => ์ค‘๋ณต ์—†์ด m๊ฐœ์˜ ์ˆ˜๋ฅผ ๊ณ ๋ฅด๊ธฐ ๋•Œ๋ฌธ

    3. ๋ฆฌ์ŠคํŠธ seq[index]์— i ๋Œ€์ž…

    4. index+1 == m์ด๋ฉด seq๋ฅผ ์ถœ๋ ฅ

    5. ์•„๋‹ˆ๋ฉด sequence( seq, n, m, index+1 ) ํ˜ธ์ถœ

# 15649-1.py

def sequence(seq, n, m, index):
    for i in range(1, n+1):
        if i in seq[:index]:
            continue
        seq[index] = i
        if index + 1 == m:
            print(' '.join(map(str, seq)))
        else:
            sequence(seq, n, m, index+1)


n, m = map(int, input().split())
nm = [0 for _ in range(m)]
sequence(nm, n, m, 0)

 

(2) ๋ฆฌ์ŠคํŠธ์— ํ•˜๋‚˜์”ฉ ์ˆซ์ž๋ฅผ ์ถ”๊ฐ€ํ•˜๋ฉฐ ๊ธธ์ด๊ฐ€ m์ด ๋˜๋ฉด ์ถœ๋ ฅํ•˜๋Š” ๋ฐฉ๋ฒ•

  def sequence( seq, n, m ) :

    1. ๋ฆฌ์ŠคํŠธ seq์˜ ๊ธธ์ด๊ฐ€ m์ธ์ง€ ํ™•์ธํ•˜์—ฌ m์ผ๋•Œ seq ์ถœ๋ ฅ

    2. i๊ฐ€ 1 ~ 1๊นŒ์ง€ ๋ฐ˜๋ณต

    3. ๋ฆฌ์ŠคํŠธ seq์— ๋Œ€์ž…ํ•˜๋ ค๋Š” i ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜์—ฌ ์žˆ์œผ๋ฉด continue => ์ค‘๋ณต ์—†์ด m๊ฐœ์˜ ์ˆ˜๋ฅผ ๊ณ ๋ฅด๊ธฐ ๋•Œ๋ฌธ

    4. ๋ฆฌ์ŠคํŠธ seq[index]์— i ์ถ”๊ฐ€

    5. sequence( seq, n, m ) ํ˜ธ์ถœ => (1)๊ณผ ๋‹ค๋ฅด๊ฒŒ seq์˜ ๊ธธ์ด๋กœ ํŒ๋‹จํ•˜๊ธฐ ๋•Œ๋ฌธ์— index๋ฅผ ์ „๋‹ฌํ•˜์ง€ ์•Š์•„๋„ ๋จ

    6. ๋ฆฌ์ŠคํŠธ seq ๋งˆ์ง€๋ง‰ ์š”์†Œ ์‚ญ์ œ

# 15649-2.py

def sequence(seq, n, m):
    if len(seq) == m:
        print(' '.join(map(str, seq)))
    for i in range(1, n+1):
        if i in seq:
            continue
        seq.append(i)
        sequence(seq, n, m)
        seq.pop()


n, m = map(int, input().split())
nm = []
sequence(nm, n, m)

 

(3) itertools ๋ชจ๋“ˆ์˜ permutations ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•

# 15649-3.py

import itertools

n, m = map(int, input().split())
nm = [str(i) for i in range(1, n+1)]

a = list(itertools.permutations(nm, m))
for i in a:
    print(' '.join(i))

 

์œ„๋ถ€ํ„ฐ ์ˆœ์„œ๋Œ€๋กœ (3) (2) (1) ๋ฒˆ ์ฝ”๋“œ

ํ™•์‹คํžˆ ๋ชจ๋“ˆ ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜๋Š”๊ฒŒ ๋น ๋ฅด๋‹ค..