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

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์™€ ๋™์ผํ•˜๋‹ค.

 

๋ฌธ์ œ

 

15663๋ฒˆ: N๊ณผ M (9)

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

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 N๊ณผ M (1 - 8)์˜ ๋ฌธ์ œ๋“ค์€ ์›์†Œ๊ฐ€ ์ค‘๋ณต๋˜์ง€๋Š” ์•Š์•˜๋‹ค. ํ•˜์ง€๋งŒ 9 - 12๋ฒˆ ๋ฌธ์ œ๋Š” ์›์†Œ๊ฐ€ ์ค‘๋ณต๋˜๋ฉฐ ๊ฐ ์š”๊ฑด์— ๋งž๊ฒŒ ์ˆœ์—ด, ์กฐํ•ฉ์„ ๊ตฌํ•˜์—ฌ์•ผ ํ•œ๋‹ค. ํ•ด๋‹น ๋ฌธ์ œ๋Š” ์ค‘๋ณต๋˜๋Š” ์›์†Œ๊ฐ€ ์žˆ์„ ๋•Œ, ์ˆœ์—ด์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ๋กœ set์„ ํ™œ์šฉํ•˜๋ฉด ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

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

from sys import stdin


def dfs(depth):
    global answer

    if depth == m:
        answer.add(tuple(nums[i] for i in check))
        return
    else:
        for i in range(n):
            if i in check:
                continue
            check[depth] = i
            dfs(depth + 1)
            check[depth] = -1


if __name__ == "__main__":
    # ์ค‘๋ณต๋œ ์ˆœ์—ด์„ ์ถ”๊ฐ€ํ•˜์ง€ ์•Š๋„๋ก set์œผ๋กœ ์„ ์–ธ
    answer = set()
    n, m = map(int, stdin.readline().split())
    nums = sorted(list(map(int, stdin.readline().split())))
    # index ๊ฐ’์„ ์ €์žฅํ•˜๋ฏ€๋กœ -1๋กœ ์ดˆ๊ธฐํ™”
    check = [-1] * m
    dfs(0)

    for num in sorted(list(answer)):
        print(*num)

 ์•ž์„œ ํ‘ผ ๋ฌธ์ œ์™€ ๋‹ค๋ฅธ ์ ์ด ์žˆ๋‹ค๋ฉด, ์ฐพ์€ ์ˆœ์—ด์„ ์ €์žฅํ•˜๋Š” answer๋ฅผ set์œผ๋กœ ์„ ์–ธํ•˜์—ฌ, ์ค‘๋ณต๋œ ๊ฐ’์„ ๋‹ด์ง€ ์•Š์•˜๋‹ค. ์—ฌ๊ธฐ์„œ ๋งํ•˜๋Š” ์ค‘๋ณต๋œ ๊ฐ’์€ (1, 7) (7, 1)๊ณผ ๊ฐ™์€ ๊ฐ’์ด ์•„๋‹Œ, (1, 7), (1, 7)์„ ์˜๋ฏธํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

 

itertools permutations๋ฅผ ํ™œ์šฉํ•œ ํ’€์ด

from itertools import permutations

N, M = map(int, input().split())
nums = map(int, input().split())

for cases in sorted(list(set(permutations(nums, M)))):
    for case in cases:
        print(case, end=' ')
    print()
728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€