BOJ 1976: 여행가자

https://www.acmicpc.net/problem/1976

  • 2월동안 187문제 풀기(지난달 누적 87개) (61/187)
  • 유니온-파인드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <bits/stdc++.h>
using namespace std;

int N, M, x, s, parent[205], height[205];

int find(int x) {
  return parent[x] = (parent[x] == x ? x : find(parent[x]));
}

void uni(int a, int b) {
  a = find(a), b = find(b);
  if(a == b) return;
  if(height[a] > height[b]) swap(a,b);
  parent[a] = b;
  if(height[a] == height[b]) ++height[b];
}

int main() {
  cin >> N >> M;
  iota(parent, parent+N+1, 0);
  for(int i = 1; i <= N; i++)
    for(int j = 1; j <= N; j++) {
      cin >> x;
      if(!x) continue;
      uni(i,j);
    }
  bool pos = true;
  cin >> s;
  s = find(s);
  for(int i = 1; i < M; i++) {
    cin >> x;
    if(find(x) != s) {
      pos = false;
      break;
    }
  }
  cout << (pos ? "YES" : "NO");
}