특정 조건에 따라 줄 세우기
- 문제 유형 : 정렬, Backtracking
- 사용언어 : Python
- 난이도 : 실버 2
- 출처 : 코드 트리
코드트리 | 코딩테스트 준비를 위한 알고리즘 정석
국가대표가 만든 코딩 공부의 가이드북 코딩 왕초보부터 꿈의 직장 코테 합격까지, 국가대표가 엄선한 커리큘럼으로 준비해보세요.
www.codetree.ai
from itertools import permutations
# 소 이름
cows = ["Bessie", "Buttercup", "Belinda", "Beatrice", "Bella", "Blue", "Betsy", "Sue"]
# N 줄
N = int(input())
#
constraints = []
for _ in range(N):
parts = input().split()
A = parts[0]
B = parts[-1]
constraints.append((A, B))
def valid_order(perm):
index_map = {cow: idx for idx, cow in enumerate(perm)}
for a, b in constraints:
if abs(index_map[a] - index_map[b]) != 1:
return False
return True
sorted_cows = sorted(cows)
for perm in permutations(sorted_cows):
if valid_order(perm):
for cow in perm:
print(cow)
break
반응형
'Programming Test > 문제풀이' 카테고리의 다른 글
[프로그래머스] 1. 옹알이 (1) - Python (0) | 2025.01.14 |
---|---|
[문제 풀이 26] 프로그래머스 - 숫자변환 (0) | 2024.09.04 |
[문제 풀이 24] 코드 트리 - n x n 표에서의 분배 (0) | 2024.04.23 |
[문제 풀이 23] 코드 트리 - n x m 표 이동 5 (0) | 2024.04.23 |
[문제 풀이 22] 코드 트리 - 색맹 (0) | 2024.04.22 |