반응형
📖 문제
https://www.acmicpc.net/problem/1240
💡 풀이 방식
• BFS
1. 인접 리스트를 만들고 N-1개의 연결 정보를 양방향으로 저장한다.
2. M개의 노드 쌍에 대해 첫 번째 노드부터 두 번째 노드까지의 거리를 구한다. (BFS)
🔺 코드
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
import java.util.*;
import java.io.*;
public class Main {
static int N,M;
static List<Node>[] graph;
static boolean[] chk;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
graph = new ArrayList[N+1];
for(int i = 1 ; i <= N ; i++) {
graph[i] = new ArrayList<>();
}
for(int i = 0 ; i < N-1 ; i++) {
st = new StringTokenizer(br.readLine(), " ");
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
// 양방향
graph[a].add(new Node(b, v));
graph[b].add(new Node(a, v));
}
while(M --> 0) {
st = new StringTokenizer(br.readLine(), " ");
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
chk = new boolean[N+1];
bfs(a, b);
}
System.out.println(sb.toString());
}
private static void bfs(int start, int end) {
Queue<Node> q = new ArrayDeque<>();
q.add(new Node(start, 0));
chk[start] = true;
while(!q.isEmpty()) {
Node now = q.poll();
if(now.idx == end) {
sb.append(now.v).append("\n");
return;
}
for(Node next : graph[now.idx]) {
if(!chk[next.idx]) {
chk[next.idx] = true;
q.add(new Node(next.idx, now.v + next.v)); // 거리 갱신
}
}
}
}
}
class Node {
int idx, v;
public Node(int idx, int v) {
this.idx = idx;
this.v = v;
}
}
|
cs |
1회독 | 2회독 | 3회독 | 4회독 | 5회독 |
V |
반응형
'코테 > 백준' 카테고리의 다른 글
[백준/JAVA] 20125번: 쿠키의 신체 측정 (1) | 2024.06.13 |
---|---|
[백준/JAVA] 10431번: 줄세우기 (0) | 2024.06.12 |
[백준/JAVA] 18429번: 근손실 (0) | 2024.06.09 |
[백준/JAVA] 10709번: 기상캐스터 (1) | 2024.06.08 |
[백준/JAVA] 14002번: 가장 긴 증가하는 부분 수열 4 (1) | 2024.06.07 |