-
Notifications
You must be signed in to change notification settings - Fork 6
/
지한얼트리.java
74 lines (52 loc) · 1.24 KB
/
지한얼트리.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class 지한얼트리 {
static boolean[] visited;
static List<Integer>[] graph;
static int answer=0;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.valueOf(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
visited = new boolean[n];
graph = new List[n];
for(int i=0; i<n;i++) {
graph[i] = new ArrayList();
}
int start=0;
for(int i=0;i<n;i++) {
int a=Integer.valueOf(st.nextToken());
if(a==-1) {
start=i;
}
else {
graph[i].add(a);
graph[a].add(i);
}
}
int delete = Integer.valueOf(br.readLine());
visited[delete]=true;
dfs(start);
System.out.println(answer);
}
public static void dfs(int node) {
int n=0;
if(visited[node]) { //방문 했다면
return;
}
//안했다면
visited[node]=true;
for(int nextnode: graph[node] ) {
if(!visited[nextnode]){//방문안했다면
n++;
dfs(nextnode);
}
}
if(n==0)//확인
answer++;
}
}