ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

N๊ณผ M ์‹œ๋ฆฌ์ฆˆ

  • ์›์†Œ๊ฐ€ ์ฃผ์–ด์ง€๋Š” ๊ฒฝ์šฐ
    • N๊ณผ M (5 ~ 8)
    • N๊ณผ M (1 ~ 4)์—์„œ ์›์†Œ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๋งŒ ์ถ”๊ฐ€ํ•˜๋ฉด ๋œ๋‹ค.
  • ์ค‘๋ณต ์›์†Œ๊ฐ€ ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ
    • 15663 N๊ณผ M (9)
    • N๊ณผ M (10 ~ 12)๋Š” (9)์™€ ๊ฐ™์ด set์„ ํ™œ์šฉํ•˜๋ฉฐ ๋กœ์ง์€ N๊ณผ M 2 - 4์™€ ๋™์ผํ•˜๋‹ค.

 

๋ฌธ์ œ

 

15652๋ฒˆ: N๊ณผ M (4)

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

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ์•ž์„œ ํ‘ผ ๋ฌธ์ œ ์ค‘ 15650 N๊ณผ M (2)๋Š” ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜์ง€ ์•Š๋Š” ์กฐํ•ฉ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์˜€๋‹ค. ํ•˜์ง€๋งŒ ์ด ๋ฌธ์ œ๋Š” N๊ฐœ์˜ ์›์†Œ๋ฅผ M๊ฐœ ์„ ํƒํ•  ๋•Œ ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜๋Š” ์กฐํ•ฉ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜์ง€ ์•Š๋Š” ์กฐํ•ฉ์— ๋Œ€ํ•œ ๋กœ์ง์„ ์ดํ•ดํ•˜์˜€๋‹ค๋ฉด ์ด ๋ฌธ์ œ๋Š” ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋‹ค. ๊ธฐ์กด ์กฐํ•ฉ์„ ๊ตฌํ•  ๋•Œ๋Š” ์žฌ๊ท€ ํ˜ธ์ถœ์„ ํ•  ๋•Œ, ํ˜„์žฌ ์„ ํƒ๋œ ์›์†Œ๋ฅผ ์„ ํƒํ•˜์ง€ ์•Š๋„๋ก ์ธ๋ฑ์Šค์— +1 ์”ฉ ์ฆ๊ฐ€์‹œ์ผœ์ฃผ์—ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋™์ผํ•œ ์ธ๋ฑ์Šค๋ฅผ ํ˜ธ์ถœ ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋ฉด ์ค‘๋ณต ์กฐํ•ฉ์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

DFS๋ฅผ ์‚ฌ์šฉํ•œ ๋ฌธ์ œ ํ’€์ด

from sys import stdin


# ์ˆœ์—ด๊ณผ ๋‹ฌ๋ฆฌ ํ˜„์žฌ ์ธ๋ฑ์Šค์˜ ๊ฐ’์ด ํ•„์š”ํ•จ.
def dfs(idx, depth):
    global answer
    # ์žฌ๊ท€ ์ข…๋ฃŒ ์กฐ๊ฑด → ์„ ํƒํ•˜๊ณ ์ž ํ•˜๋Š” ์ˆ˜
    if depth == m:
        answer.append([*check])
    else:
        for i in range(idx, n):
            check[depth] = i + 1
            dfs(i, depth + 1)

if __name__ == '__main__':
    answer = []
    n, m = map(int, stdin.readline().split())
    check = [0] * m
    dfs(0, 0)

    for num in answer:
        print(*num)

 

itertools combinations_with_replacement๋ฅผ ํ™œ์šฉํ•œ ๋ฌธ์ œ ํ’€์ด

from itertools import combinations_with_replacement

N, M = map(int, input().split())
nums = [num + 1 for num in range(N)]
for cases in combinations_with_replacement(nums, M):
    for case in cases:
        print(case, end=' ')
    print()
728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€