Post

[BOJ] 15657. N๊ณผ M (8)(python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

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

  1. ๋น„๋‚ด๋ฆผ์ฐจ์ˆœ ๋ฐฐ์—ด
    arr[i-1] <= arr[i]๋กœ ์ •๋ ฌ๋˜์–ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ž…๋ ฅ๋ฐ›์€ ๋ฐฐ์—ด์„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค.

  2. ๋ถ€๋ถ„ ์ˆ˜์—ด ๋งŒ๋“ค๊ธฐ
    ๋น„๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋˜์–ด์žˆ๊ธฐ ๋•Œ๋ฌธ์— ํ˜„์žฌ์œ„์น˜๋ณด๋‹ค ์™ผ์ชฝ์— ์žˆ๋Š” ์ˆ˜๋Š” ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค.
    ์ค‘๋ณต๋˜๋Š” ์ˆ˜๋ฅผ ํฌํ•จํ•œ ๋ฐฐ์—ด์€ ํ˜„์žฌ ์œ„์น˜๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•  ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— ์™ผ์ชฝ์— ์žˆ๋Š” ์ˆ˜๋Š” ํƒ์ƒ‰ํ•˜์ง€ ์•Š์•„๋„ ๋œ๋‹ค.
    ๊ทธ๋ž˜์„œ ํ˜„์žฌ ์œ„์น˜์—์„œ๋ถ€ํ„ฐ n๊นŒ์ง€ ๋ฐฐ์—ด์— i๋ฒˆ์งธ ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.

  3. ์ค‘๋ณต ์ฒดํฌํ•˜๊ธฐ
    ๋งŒ๋“ค์–ด์ง„ ๋ฐฐ์—ด์ด ์ค‘๋ณต๋˜๋ฉด ๋”์ด์ƒ ๊ทธ ์ˆ˜์—ด์€ ํƒ์ƒ‰ํ•˜์ง€ ์•Š๋Š”๋‹ค. ์ค‘๋ณต๋˜์ง€ ์•Š์„ ๊ฒฝ์šฐ 2๋ฒˆ๊ณผ์ •์„ ๊ณ„์† ์ˆ˜ํ–‰ํ•œ๋‹ค.

  4. m๊ฐœ ๋น„๋‚ด๋ฆผ์ฐจ์ˆœ ๋ถ€๋ถ„์ˆ˜์—ด
    ๋งŒ๋“ค์–ด์ง„ ๋ฐฐ์—ด์˜ ๊ธธ์ด๊ฐ€ m์ด๋ฉด ์ถœ๋ ฅํ•˜๊ณ  ํƒ์ƒ‰์„ ๋ฉˆ์ถ˜๋‹ค.

๐Ÿฅ‚์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import sys; input = sys.stdin.readline
n, m = map(int,input().split())
arr = sorted(list(map(int,input().split())))
tmp = []
chk = set()

def isDuplicate(li):
    if li not in chk: 
        chk.add(li)
        return True
    return False

def dfs(inx):
    if len(tmp) == m:
        print(' '.join(map(str,tmp)))
        return
    for i in range(inx,n):
        tmp.append(arr[i])
        if isDuplicate(tuple(tmp)):
            dfs(i)
        tmp.pop()
dfs(0)
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.