|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.StringTokenizer; |
| 4 | + |
| 5 | +public class BJ_1976_여행_가자 { |
| 6 | + |
| 7 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 8 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 9 | + private static StringTokenizer st; |
| 10 | + |
| 11 | + private static int N, M; |
| 12 | + private static int[] parents; |
| 13 | + |
| 14 | + public static void main(String[] args) throws IOException { |
| 15 | + init(); |
| 16 | + sol(); |
| 17 | + |
| 18 | + bw.flush(); |
| 19 | + bw.close(); |
| 20 | + br.close(); |
| 21 | + } |
| 22 | + |
| 23 | + private static void init() throws IOException { |
| 24 | + N = Integer.parseInt(br.readLine()); |
| 25 | + M = Integer.parseInt(br.readLine()); |
| 26 | + |
| 27 | + parents = new int[N + 1]; |
| 28 | + for (int i = 1; i <= N; i++) { |
| 29 | + parents[i] = i; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + private static void sol() throws IOException { |
| 34 | + for (int i = 1; i <= N; i++) { |
| 35 | + st = new StringTokenizer(br.readLine()); |
| 36 | + for (int j = 1; j <= N; j++) { |
| 37 | + if (st.nextToken().equals("0")) continue; |
| 38 | + |
| 39 | + union(i, j); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + st = new StringTokenizer(br.readLine()); |
| 44 | + int v = Integer.parseInt(st.nextToken()); |
| 45 | + while (M-- > 1) { |
| 46 | + int u = Integer.parseInt(st.nextToken()); |
| 47 | + |
| 48 | + if (find(v) != find(u)) { |
| 49 | + bw.write("NO\n"); |
| 50 | + return; |
| 51 | + } |
| 52 | + } |
| 53 | + bw.write("YES\n"); |
| 54 | + } |
| 55 | + |
| 56 | + private static int find(int a) { |
| 57 | + if (parents[a] == a) return a; |
| 58 | + |
| 59 | + return parents[a] = find(parents[a]); |
| 60 | + } |
| 61 | + |
| 62 | + private static void union(int a, int b) { |
| 63 | + int rootA = find(a); |
| 64 | + int rootB = find(b); |
| 65 | + |
| 66 | + if (rootA < rootB) { |
| 67 | + parents[rootB] = rootA; |
| 68 | + } else { |
| 69 | + parents[rootA] = rootB; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | +} |
| 74 | +``` |
0 commit comments