์ต๋จ ๊ฒฝ๋ก๋ฅผ ์ฐพ๋ ๊ฒ๋ ์๋๊ณ , ๋ค๋ฅธ ๋์๋ฅผ ๊ฑฐ์ณ์๋ผ๋ ๋ค๋ฅผ ์๋ง ์์ผ๋ฉด ๋๋ค.
์ ๋์จ ํ์ธ๋๋ก ๊ฐ ๋์๋ค์ ์ต์์ parent๋ฅผ ์ฐพ๊ณ , ๊ฒฝ๋ก์์ ๋์๋ค์ด ๊ฐ์ parent์ธ์ง๋ง ์ฒดํฌํ๋ฉด ๋๋ค.
/* 2021.01.02(ํ ) */
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main{
static int[] parent;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine().trim());
int M = Integer.parseInt(br.readLine().trim());
parent = new int[N+1];
for(int i=1;i<=N;i++) parent[i] = i;
//์ ๋์จ ๊ณผ์
String[] str;
int start,end, value;
for(int a=1;a<=N;a++) {
str = br.readLine().trim().split(" ");
start = a;
for(int b=1;b<=N;b++) {
value = Integer.parseInt(str[b-1]);
if(value==0) continue;
end = b;
union(start,end);
}
}
//๊ฒฝ๋ก ์ฒดํฌ
str = br.readLine().trim().split(" ");
int prevParent = -1;
int city;
String result = "YES";
for(int i=0;i<M;i++) {
city = Integer.parseInt(str[i]);
if(i==0) prevParent = parent[city];
if(prevParent!=find(city)) {
result = "NO";
break;
}
}
System.out.println(result);
}
private static void union(int start, int end) {
start = find(start);
end = find(end);
if(start==end) return;
if(start<end) {
parent[end] = start;
}else if(start>end){
parent[start] = end;
}
}
private static int find(int n) {
if(parent[n]==n) return n;
return parent[n] = find(parent[n]);
}
}
'์๊ณ ๋ฆฌ์ฆ > ๋ฌธ์ ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์๋ฐ] ๋ฐฑ์ค 1197 - ์ต์ ์คํจ๋ ํธ๋ฆฌ (0) | 2021.01.05 |
---|---|
[์๋ฐ] 2019 ์นด์นด์ค ๊ฐ๋ฐ์ ๊ฒจ์ธ ์ธํด์ญ - #3 ๋ถ๋ ์ฌ์ฉ์ (0) | 2021.01.02 |
[์๋ฐ] ๋ฐฑ์ค 1717 - ์งํฉ์ ํํ (0) | 2020.12.29 |
[์๋ฐ] ๋ฐฑ์ค 1956 - ์ด๋ (0) | 2020.12.24 |
[์๋ฐ] ๋ฐฑ์ค 11404 - ํ๋ก์ด๋ (0) | 2020.12.19 |