Skip to content

Commit ff63cb0

Browse files
committed
[Silver II] Title: 트리의 부모 찾기, Time: 484 ms, Memory: 61576 KB -BaekjoonHub
1 parent 9345db3 commit ff63cb0

File tree

2 files changed

+33
-27
lines changed

2 files changed

+33
-27
lines changed

백준/Silver/11725. 트리의 부모 찾기/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
44

55
### 성능 요약
66

7-
메모리: 61732 KB, 시간: 492 ms
7+
메모리: 61576 KB, 시간: 484 ms
88

99
### 분류
1010

1111
그래프 이론, 그래프 탐색, 트리, 너비 우선 탐색, 깊이 우선 탐색
1212

1313
### 제출 일자
1414

15-
2024년 7월 13일 19:15:15
15+
2025년 3월 8일 08:07:18
1616

1717
### 문제 설명
1818

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,57 @@
11
import java.io.*;
22
import java.util.*;
3-
public class Main {
43

4+
public class Main {
55
static int n;
66
static int[] p;
7-
static List<Integer>[] graph;
7+
static List<Integer>[] tree;
88
static StringTokenizer st;
99
static StringBuilder sb = new StringBuilder();
10+
1011
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
12+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
1113
public static void main(String[] args) throws Exception{
12-
input();
13-
dfs(1, 0);
14-
for (int i = 2; i < n + 1; i++) {
15-
sb.append(p[i]).append("\n");
16-
}
17-
System.out.println(sb);
14+
preSetting();
15+
dfs(0, 1);
16+
print();
17+
18+
}
19+
20+
static void print() throws Exception{
21+
for(int i = 2; i < n + 1; i++) sb.append(p[i]).append("\n");
22+
bw.append(sb);
23+
bw.close();
1824
}
1925

20-
public static void dfs(int now, int pre){
26+
static void dfs(int pre, int now){
2127

2228
int next;
23-
for (int i = 0; i < graph[now].size(); i++) {
24-
next = graph[now].get(i);
25-
if(next == pre) continue;
29+
for(int i = 0; i < tree[now].size(); i++){
30+
next = tree[now].get(i);
2631

32+
if(next == pre) continue;
2733
p[next] = now;
28-
dfs(next, now);
34+
dfs(now, next);
2935
}
3036
}
3137

32-
public static void input () throws Exception{
38+
static void preSetting() throws Exception{
3339
n = Integer.parseInt(br.readLine());
40+
3441
p = new int[n + 1];
35-
graph = new ArrayList[n + 1];
36-
for (int i = 0; i < n + 1; i++) {
37-
graph[i] = new ArrayList<>();
38-
}
42+
tree = new ArrayList[n + 1];
3943

40-
int u, v;
41-
for (int i = 0; i < n - 1; i++) {
44+
p[1] = 1;
45+
for(int i = 0; i < n + 1; i++) tree[i] = new ArrayList<>();
46+
47+
int a, b;
48+
for(int i = 0 ; i < n - 1; i++) {
4249
st = new StringTokenizer(br.readLine());
43-
u = Integer.parseInt(st.nextToken());
44-
v = Integer.parseInt(st.nextToken());
50+
a = Integer.parseInt(st.nextToken());
51+
b = Integer.parseInt(st.nextToken());
4552

46-
graph[u].add(v);
47-
graph[v].add(u);
53+
tree[a].add(b);
54+
tree[b].add(a);
4855
}
4956
}
50-
5157
}

0 commit comments

Comments
 (0)