Notice
Recent Posts
문제 풀이 및 개발 공간
[백준] 1976번 여행 가자 (gold 4 본문
import java.io.*;
import java.util.*;
public class Main{
static int[] num;
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
int n=Integer.valueOf(br.readLine());
int m=Integer.valueOf(br.readLine());
num=new int[n+1];
for(int i=1; i<=n; i++){
num[i]=i;
}
int[][] map=new int[n+1][n+1];
for(int i=1; i<=n; i++){
st=new StringTokenizer(br.readLine());
for(int j=1; j<=n; j++){
map[i][j]=Integer.valueOf(st.nextToken());
}
}
//유니온을 써서 그래프 정점들간의 관계
//겹칠애들 겹침
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
if(map[i][j]==1){
Union(i,j);
}
}
}
st=new StringTokenizer(br.readLine());
boolean is=true;
int temp=num[Find(Integer.valueOf(st.nextToken()))];
for(int i=1; i<m; i++){
int t=Integer.valueOf(st.nextToken());
//Find가 결국 부모를 반환하므로 이를 이용해서 최초의 부모와 계속 같은지
if(temp!=Find(num[t])){
is=false;
break;
}
}
bw.write(is ? "YES" : "NO");
bw.flush();
}
public static int Find(int v){
if(v==num[v]){
return v;
}
else{
return v=Find(num[v]);
}
}
public static void Union(int a, int b){
int fa=Find(a);
int fb=Find(b);
if(fa!=fb){
num[fa]=fb;
}
}
}
//유니온 파인드를 사용하면 간단하게 해결가능한 문제.
//유니온 파인드를 연습하려고 해결한 문제.
'백준공부 > java' 카테고리의 다른 글
[백준] 1717번 집합의 표현 (gold 5 (0) | 2024.03.14 |
---|---|
[백준] 2535번 아시아 정보올림피아드 (silver 5 (0) | 2024.03.13 |
[백준] 2887번 행성 터널 (platinum 5 (0) | 2024.03.13 |
[백준] 37474번 양갈래 짝 맞추기 (silver 4 (0) | 2024.03.12 |
[백준] 31472번 갈래의 색종이 자르기 (bronze 3 (0) | 2024.03.12 |