분리집합 문제. union-find로 묶고 다른게 있으면 No 한집단이면 YES
import sys
input = sys.stdin.readline
def union(x, y):
x = find(x)
y = find(y)
if x > y:
x, y = y, x
parents[y] = x
def find(x):
if parents[x] == x:
return x
parents[x] = find(parents[x])
return parents[x]
N = int(input())
M = int(input())
edges = [list(map(int, input().split())) for _ in range(N)]
plan = list(map(lambda x: int(x) - 1, input().split()))
parents = {i: i for i in range(N)}
for i in range(N):
for j in range(N):
if edges[i][j] and find(i) != find(j):
union(i, j)
pivot = find(plan[0])
for city in plan[1:]:
if find(city) != pivot:
print('NO')
break
else:
print('YES')
'practivceAlgorithm > 백준' 카테고리의 다른 글
[백준][Python] 2920 음계 (0) | 2021.10.23 |
---|---|
[백준][Python] 2475 검증수 (0) | 2021.10.23 |
[백준][Python] 17451 평행우주 (0) | 2021.10.21 |
[백준][Python] 2776 암기왕 (0) | 2021.10.21 |
[백준][Python] 20168 골목대장 호석 (0) | 2021.10.20 |