(Challenge)BFS Special Judge
import java.util.*;
public class BFS_SpecialJudge_2nd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<Integer>[] a = new ArrayList[n];
int[] parent = new int[n];//n๋งํผ ์์ฑํ๋ ๊ฒ ๋ง๋?
boolean[] c = new boolean[n];
int[] order = new int[n];
for(int i=0;i<n;i++) {
a[i] = new ArrayList<>();
}
for(int i=0;i<n-1;i++) {//๊ฐ์ ์ ๋ณด ์ ์ฅ~
int u = sc.nextInt()-1;
int v = sc.nextInt()-1;
a[u].add(v);a[v].add(u);
}
for(int i=0;i<n;i++) {
order[i] = sc.nextInt()-1;
}
//์ธ์ ๋
ธ๋๋ฅผ ๋๋ฉด์ ์ธ์ ๋
ธ๋ ๊ด๊ณ๋ฅผ ๋ํ๋ด๋ parent๋ฐฐ์ด์ ์์ฑํ๊ณ , ํ์ฌ ์ ์ x์ ์ธ์ ๋
ธ๋ ๊ฐฏ์๋ฅผ ์ธ์ค๋ค!
Queue<Integer> q = new LinkedList<Integer>();
q.add(0);c[0] = true;
int m=1;
for(int i=0;i<n;i++) {//i๋ 0๋ถํฐ ์ ์ ๊ฐฏ์๋งํผ ๋ฐ๋ณตํ๋ค. order[0]๋ถํฐ order[n-1]๊น์ง.
//Round1.ํ์์ ๊บผ๋ธ x(0)์ order[0] ๋น๊ต.
//Round2.x(0)์ ์ธ์ ๋
ธ๋๋ฅผ ํ์ ๋ฃ์๊ธฐ ๋๋ฌธ์
// x(0)์ ์ธ์ ๋
ธ๋์ order[1]๊ณผ ๋น๊ต. - x์ ์ธ์ ๋
ธ๋ : 1,2 ์ด๊ณ order:0 1 2 3 ๋๋ 0 2 1 3์ผ ๋
//parent[1] = 0, parent[2] = 0 1,2 ๋๋ค parent ๊ฐ์ด x์ด๋ฏ๋ก(์ธ์ ๋
ธ๋๊ฐ x) ๋ง์กฑ~!
//์ด๋ฌํ n๊ฐ์ ์ ์ ์ ๋ํด order์ ๊ฐ ๊ฐ๊ณผ ๋น๊ต ์ฐ์ฐ์ n๊ฐ ๋งํผ๋ฐ๋ณตํ๊ธฐ ๋๋ฌธ์ for(i=0~n)๋๋ ค์ค๋ค!
if(q.isEmpty()) {//ํ๊ฐ ๋น๋ฉด? bfs ๋ค ๋์๋ค๋ ๋ป.๊ทผ๋ฐ ์ 0์ถ๋ ฅํ๊ณ ์ข
๋ฃํ๋?
System.out.println(0);
System.exit(0);
}
int x = q.remove();
if(x != order[i]) {
System.out.println(0);
System.exit(0);
}
int cnt=0;
for(int y:a[x]) {
if(c[y]==false) {
parent[y] = x;cnt++;//์ธ์ ๋
ธ๋ ๊ฐฏ์ ์ผ๋ค!
}
}
for(int j=0;j<cnt;j++) {
if(m+j>=n || parent[order[m+j]] != x) {
System.out.println(0);
System.exit(0);
}
q.add(order[m+j]);
c[order[m+j]]=true;
}
m+=cnt;
}
System.out.println(1);
}
}
Last updated