반응형
https://www.acmicpc.net/problem/1976
1976번: 여행 가자
동혁이는 친구들과 함께 여행을 가려고 한다. 한국에는 도시가 N개 있고 임의의 두 도시 사이에 길이 있을 수도, 없을 수도 있다. 동혁이의 여행 일정이 주어졌을 때, 이 여행 경로가 가능한 것인지 알아보자. 물론 중간에 다른 도시를 경유해서 여행을 할 수도 있다. 예를 들어 도시가 5개 있고, A-B, B-C, A-D, B-D, E-A의 길이 있고, 동혁이의 여행 계획이 E C B C D 라면 E-A-B-C-B-C-B-D라는 여행경로를 통해 목적을 달성할
www.acmicpc.net

Union-find 문제.
This file contains hidden or 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
cities = int(input()) | |
_ = int(input()) | |
parent = {i:i for i in range(1, cities+1)} | |
def parent_find(x): | |
if x == parent[x]: | |
return x | |
p = parent_find(parent[x]) | |
parent[x] = p | |
return parent[x] | |
def union(x,y): | |
x = parent_find(x) | |
y = parent_find(y) | |
if x != y: | |
parent[y] = x | |
for y in range(1, cities+1): | |
maps = list(map(int, input().split())) | |
for x in range(1, len(maps)+1): | |
# 갈 수 있는 도시라면, 전부 y 기준으로 맞춘다. | |
if maps[x-1] == 1: | |
union(y, x) | |
tour = list(map(int, input().split())) | |
result = set([parent_find(i) for i in tour]) | |
if len(result) != 1: | |
print("NO") | |
else: | |
print("YES") | |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] 프로그래머스. 예산 (Level 3) (0) | 2020.02.08 |
---|---|
[Python] 백준 15997. 승부 예측 (카카오 코드페스티벌 2018) (0) | 2020.02.07 |
[Python] 백준 17472. 다리만들기2 (0) | 2020.02.04 |
[Python] 백준 2573. 빙산 (0) | 2020.02.03 |
[Python] 백준 10799. 쇠막대기 (0) | 2020.02.01 |