Preparing Coding Test/Algorithm
[Java/백준/DFS] 16964번: DFS 스페셜 저지
weero
2021. 3. 9. 01:36
문제
16964번: DFS 스페셜 저지
첫째 줄에 정점의 수 N(2 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N-1개의 줄에는 트리의 간선 정보가 주어진다. 마지막 줄에는 DFS 방문 순서가 주어진다. DFS 방문 순서는 항상 N개의 정수로 이루
www.acmicpc.net
계속 99%에서 틀렸습니다가 떠서 환장했던 문제ㅠㅠ
import java.io.*;
import java.util.*;
public class Main {
static int N;
static ArrayList<Integer>[] adjacent;
static boolean[] visited;
static int[] compArr2;
static StringBuilder sb = new StringBuilder();
static int index = 0;
private static void dfs(int pos) {
if (pos != compArr2[index++]) {
System.out.println(0);
System.exit(0);
}
visited[pos] = true;
if (index < N)
dfs(compArr2[index]);
for (int e : adjacent[pos]) {
if (!visited[e]) {
dfs(e);
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
adjacent = new ArrayList[N + 1];
visited = new boolean[N + 1];
for (int i = 1; i < N + 1; i++) {
adjacent[i] = new ArrayList<Integer>();
}
for (int i = 0; i < N - 1; i++) {
String[] info = br.readLine().split("\\s");
int a = Integer.parseInt(info[0]);
int b = Integer.parseInt(info[1]);
adjacent[a].add(b);
adjacent[b].add(a);
}
for (int i = 1; i < N + 1; i++) {
Collections.sort(adjacent[i]);
}
String comp = br.readLine();
String[] compArr = comp.split("\\s");
compArr2 = new int[N];
for (int i = 0; i < N; i++) {
compArr2[i] = Integer.parseInt(compArr[i]);
}
dfs(1);
System.out.println(1);
br.close();
}
}
질문에서 비슷한 문제가 나왔던 사람들은 맨 처음이 1이 아닐 경우를 체크 안해줘서라는데
나는 그 경우도 되는 거 아닌가... 뭘까..