File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.util.* ;
3+
4+ public class Main {
5+ static int [] parent;
6+
7+ public static void main (String [] args ) {
8+ Scanner sc = new Scanner (System . in);
9+ int N = sc. nextInt();
10+ int M = sc. nextInt();
11+
12+ parent = new int [N + 1 ];
13+ for (int i = 1 ; i <= N ; i++ ) {
14+ parent[i] = i;
15+ }
16+ for (int i = 1 ; i <= N ; i++ ) {
17+ for (int j = 1 ; j <= N ; j++ ) {
18+ int connected = sc. nextInt();
19+ if (connected == 1 ) {
20+ union(i, j);
21+ }
22+ }
23+ }
24+
25+ int [] plan = new int [M ];
26+ for (int i = 0 ; i < M ; i++ ) {
27+ plan[i] = sc. nextInt();
28+ }
29+
30+ int root = find(plan[0 ]);
31+ boolean possible = true ;
32+ for (int i = 1 ; i < M ; i++ ) {
33+ if (find(plan[i]) != root) {
34+ possible = false ;
35+ break ;
36+ }
37+ }
38+
39+ System . out. println(possible ? " YES" : " NO" );
40+ }
41+
42+ static int find (int x ) {
43+ if (x != parent[x]) {
44+ parent[x] = find(parent[x]);
45+ }
46+ return parent[x];
47+ }
48+
49+ static void union (int a , int b ) {
50+ int rootA = find(a);
51+ int rootB = find(b);
52+ if (rootA != rootB) {
53+ parent[rootB] = rootA;
54+ }
55+ }
56+ }
57+
58+ ```
You can’t perform that action at this time.
0 commit comments