[BaekJoon] ๋ฐฑ์ค€ 15663๋ฒˆ : N๊ณผ M (9)

Updated:

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


๋‹ค๋ฅธ N๊ณผ M ๋ฌธ์ œ์— ๋น„ํ•ด ํ•ด๊ฒฐ๋ฐฉ๋ฒ•์„ ์ฐพ๊ธฐ ์–ด๋ ค์› ๋˜ ๋ฌธ์ œ์˜€๋‹ค..

๋‚ด๊ฐ€ ์ƒ๊ฐํ•œ ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•์€ ์ฃผ์–ด์ง„ ์ž์—ฐ์ˆ˜ ์ค‘ ์ค‘๋ณต ๊ฐ’์„ ์ฐพ์•„ ๋”ฐ๋กœ ์ €์žฅ์„ ํ•œ๋‹ค.

๊ทธ๋ฆฌ๊ณ  ์ฃผ์–ด์ง„ ์ž์—ฐ์ˆ˜ ๋ฐฐ์—ด์„ set ์œผ๋กœ ๋ฐ”๊พธ์–ด ์ค‘๋ณต ๊ฐ’์„ ์—†์• ๊ณ  ์ด set ์œผ๋กœ ์ˆœ์—ด์„ ๋งŒ๋“ ๋‹ค.

4 3

2 4 4 9 ์ด๋ ‡๊ฒŒ ๋ฐฐ์—ด์ด ์ฃผ์–ด์ง„ ๊ฒฝ์šฐ ์ค‘๋ณต ๊ฐ’ 4 ๋ฅผ ๋”ฐ๋กœ ์ €์žฅํ•œ ๋’ค 2 4 9 ๋ฐฐ์—ด๋กœ ๋งŒ๋“ค๊ณ  ์ˆœ์—ด์„ ๋งŒ๋“œ๋Š” ๊ฒƒ ์ด๋‹ค.

image

๊ทธ๋ ‡๊ฒŒ ๋˜๋ฉด ์ด๋Ÿฐ ๊ฒฝ์šฐ๊ฐ€ ์ƒ๊ธฐ๋Š”๋ฐ ๋…ธ๋ž€์ƒ‰ ํ˜•๊ด‘์น ์ด ๋œ ๊ฒฝ์šฐ๊ฐ€ ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ์ด๋‹ค.

๋‹ต์ด ์•„๋‹Œ ๊ฒฝ์šฐ๋Š” ๋‘ ๊ฐ€์ง€ ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค.

์ฒซ ๋ฒˆ์งธ๋กœ 2 2 ๊ฐ™์ด ์ค‘๋ณต ๊ฐ’์ด ์•„๋‹Œ๋ฐ ๋˜ append ๋ฅผ ํ•˜๋Š” ๊ฒฝ์šฐ ๋ฐ”๋กœ continue ๋ฅผ ํ•œ๋‹ค.

๋‘ ๋ฒˆ์งธ๋กœ 4 4 4 ๊ฐ™์ด 4 4 ๋Š” ๊ฐ€๋Šฅํ•˜์ง€๋งŒ ๋˜ 4 ๊ฐ€ ๋“ค์–ด์˜ค๋ฉด ์•ˆ๋˜๋Š” ๊ฒฝ์šฐ์ด๋‹ค.

์ด ๊ฒฝ์šฐ๋ฅผ Counter ๋ฅผ ์ด์šฉ ํ•ด ์ฐพ์•„์ฃผ์—ˆ๋‹ค.

์ฒ˜์Œ ์ฃผ์–ด์ง„ ์ค‘๋ณต ๊ฐ’์˜ ๊ฐœ์ˆ˜๋ณด๋‹ค ์Šคํƒ์— ์žˆ๋Š” ์ค‘๋ณต ๊ฐ’์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋” ๋งŽ์•„์ง€๋ฉด ๋ฐ”๋กœ continue ๋ฅผ ํ•œ๋‹ค.

์˜ˆ๋ฅผ๋“ค์–ด ์ฒ˜์Œ ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์—์„œ ์ค‘๋ณต ๊ฐ’ 4 ๋Š” ๋‘ ๊ฐœ์˜€๋Š”๋ฐ ์Šคํƒ์ด 4 4 ์ธ ๊ฒฝ์šฐ 4 ๋ฅผ ๋˜ ๋„ฃ์–ด์ฃผ๋ฉด ์ค‘๋ณต ๊ฐ’์˜ ๊ฐœ์ˆ˜๊ฐ€ ์„ธ ๊ฐœ๊ฐ€ ๋œ๋‹ค.

์ด๋ ‡๊ฒŒ ๋‘ ๊ฐ€์ง€ ๊ฒฝ์šฐ๋ฅผ ์ œ์™ธ์‹œ์ผœ์ฃผ๋ฉด ๋‹ต์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

๋ฌผ๋ก  Permutation ๊ณผ set ์„ ์ด์šฉํ•˜๋ฉด ์ฝ”๋“œ ํ•œ ์ค„๋กœ ํ•ด๊ฒฐ์ด ๊ฐ€๋Šฅํ•˜๋‹ค..


import sys
from collections import Counter


def DFS():
	if len(stack) == m:
		print(*stack)
		return

	for i in range(len(data)):
		if stack and data[i] in stack and data[i] not in duplicate:
			continue
		if data[i] in duplicate and count[data[i]] < Counter(stack)[data[i]] + 1:
			continue
		stack.append(data[i])
		DFS()
		stack.pop()


n, m = map(int, sys.stdin.readline().rsplit())
data = list(map(int, sys.stdin.readline().rsplit()))
count = Counter(data)
stack = []
duplicate = []

for key, value in zip(count.keys(), count.values()):
	if value > 1:
		duplicate.append(key)
data = sorted(list(set(data)))

DFS()

import sys
from itertools import permutations


n, m = map(int, sys.stdin.readline().rsplit())
data = map(int, sys.stdin.readline().rsplit())

for val in sorted(list(set(permutations(data, m)))):
	print(*val)



Categories:

Updated:

Leave a comment