[Link] https://www.acmicpc.net/problem/1976
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
39
40
41
42
43
44
45
46
47
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader br;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
String[] line;
int n = toi(br.readLine()), m = toi(br.readLine());
int[][] link = new int[n][n];
int[] union = new int[n];
for(int i = 0; i < n; i++) union[i] = i;
for(int i = 0; i < n; i++) {
line = getLine();
for(int j = 0; j < n; j++) {
if(line[j].equals("1")) {
link[i][j] = 1;
int parentI = getTop(i, union), parentJ = getTop(j, union);
if(parentI < parentJ) union[parentJ] = parentI;
else if(parentI != parentJ) union[parentI] = parentJ;
}
}
}
line = getLine();
int topNode = getTop((toi(line[0]) - 1) , union);
for(int i = 1; i < line.length; i++) {
if(topNode != getTop((toi(line[i]) - 1), union)) {
print("NO");
return;
}
}
print("YES");
}
static int getTop(int idx, int[] union) {
if(union[idx] == idx) return union[idx];
return union[idx] = getTop(union[idx], union);
}
static int toi(String s) { return Integer.parseInt(s); }
static String[] getLine() throws IOException { return br.readLine().split(" "); }
static <T> void print(T s) { System.out.print(s); }
static <T> void println(T s) { System.out.println(s); }
}