728x90
1. 링크
https://www.acmicpc.net/problem/15654
2. 난이도(solved.ac 참고)
실버3
3. 풀이
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://www.acmicpc.net/problem/15654 | |
from itertools import permutations | |
import sys | |
f = sys.stdin.readline | |
n, m = map(int, f().split()) | |
a = list(map(int, f().split())) | |
for i in permutations(sorted(a), m): | |
if len(i) == 1: | |
print(i[0]) | |
else: | |
print(*i) |
다르게 풀 수도 있겠지만, 나는 permutations(순열) 모듈을 불러와서 사용했다. 순열은 수학에서 nPr이다. n개 중에 r개를 뽑는 경우의 수이다.
<python />
from itertools import permutations
a = [1, 2, 3, 4]
for i in permutations(a, 2):
print(i)
# (1, 2)
# (1, 3)
# (1, 4)
# (2, 1)
# (2, 3)
# (2, 4)
# (3, 1)
# (3, 2)
# (3, 4)
# (4, 1)
# (4, 2)
# (4, 3)
사전 순서로 증가하는 순으로 출력해야 되었기 때문에 a를 정렬한 값을 기준으로 순열을 돌렸다.
기본적으로 튜플의 형태로 출력이 되기 때문에 스페이스바로 값을 구분하는 것 외에 모든 요소를 무시하는 *i로 출력을 해줬다. 순열의 값이 1개일 경우에는, 그러니까 nPr에서 r이 1인 경우는 그냥 i[0]만 출력하게 했는데, 이는 값이 1개라면 (1,) 와 같은 형태로 출력이 되기 때문에 *i로도 출력이 불가능하다(두 개의 요소를 필요로 하기 때문이다). 그래서 그냥 i[0]만 출력하게 한 것이다.
'CS > 알고리즘' 카테고리의 다른 글
[Python] BOJ(백준) 12904번 - A와 B (0) | 2021.08.30 |
---|---|
[Python] BOJ(백준) 4358번 - 생태학 (+defaultdict) (0) | 2021.08.30 |
[PyPy3] BOJ(백준) 17626번 - Four Squares (0) | 2021.08.26 |
[Python] BOJ(백준) 1013번 - Contact (0) | 2021.08.25 |
[백준] 아이디 색상 변경하기 (0) | 2021.08.20 |