Skip to content

Commit c04310c

Browse files
authored
[20250723] BOJ / G5 / 노드사이의 거리 / 김수연
1 parent 7e250ec commit c04310c

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
public class boj1240 {
6+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
static StringTokenizer st;
8+
static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());}
9+
static int nextInt() {return Integer.parseInt(st.nextToken());}
10+
static ArrayList<Node>[] map;
11+
static boolean[] visit;
12+
static int n;
13+
static int max;
14+
15+
public static void main(String[] args) throws Exception {
16+
nextLine();
17+
n = nextInt();
18+
int m = nextInt();
19+
map = new ArrayList[n];
20+
visit = new boolean[n];
21+
22+
for (int i = 0; i < n; i++) {
23+
map[i] = new ArrayList<>();
24+
}
25+
26+
for (int i = 0; i < n - 1; i++) {
27+
nextLine();
28+
int a = nextInt() - 1;
29+
int b = nextInt() - 1;
30+
int d = nextInt();
31+
map[a].add(new Node(b, d));
32+
map[b].add(new Node(a, d));
33+
}
34+
35+
for (int i = 0; i < m; i++) {
36+
nextLine();
37+
int a = nextInt() - 1;
38+
int b = nextInt() - 1;
39+
dfs(a, b, 0);
40+
System.out.println(max);
41+
max = 0;
42+
visit = new boolean[n];
43+
}
44+
}
45+
46+
static void dfs(int start, int end, int dist) {
47+
if (start == end) {
48+
max = dist;
49+
return;
50+
}
51+
52+
visit[start] = true;
53+
for (int i = 0; i < map[start].size(); i++) {
54+
if (!visit[map[start].get(i).next]) {
55+
dfs(map[start].get(i).next, end, dist + map[start].get(i).dist);
56+
}
57+
}
58+
}
59+
}
60+
61+
class Node {
62+
int next;
63+
int dist;
64+
65+
public Node(int next, int dist) {
66+
this.next = next;
67+
this.dist = dist;
68+
}
69+
}
70+
```

0 commit comments

Comments
 (0)