|
| 1 | +``` |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | +
|
| 5 | +public class Main { |
| 6 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 8 | + private static List<Edge>[] edges; |
| 9 | + private static boolean[] visited; |
| 10 | + private static int N, start, end; |
| 11 | +
|
| 12 | + public static void main(String[] args) throws IOException { |
| 13 | + init(); |
| 14 | +
|
| 15 | + int answer = BFS(); |
| 16 | +
|
| 17 | + bw.write(answer + "\n"); |
| 18 | + bw.flush(); |
| 19 | + bw.close(); |
| 20 | + br.close(); |
| 21 | + } |
| 22 | +
|
| 23 | + private static void init() throws IOException { |
| 24 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 25 | + N = Integer.parseInt(st.nextToken()); |
| 26 | + start = Integer.parseInt(st.nextToken()); |
| 27 | + end = Integer.parseInt(st.nextToken()); |
| 28 | +
|
| 29 | + edges = new List[N+1]; |
| 30 | + visited = new boolean[N+1]; |
| 31 | +
|
| 32 | + for (int i = 1; i <= N; i++) { |
| 33 | + edges[i] = new ArrayList<>(); |
| 34 | + } |
| 35 | +
|
| 36 | + for (int i = 1; i < N; i++) { |
| 37 | + st = new StringTokenizer(br.readLine()); |
| 38 | + int node1 = Integer.parseInt(st.nextToken()); |
| 39 | + int node2 = Integer.parseInt(st.nextToken()); |
| 40 | + int cost = Integer.parseInt(st.nextToken()); |
| 41 | + edges[node1].add(new Edge(node2, cost)); |
| 42 | + edges[node2].add(new Edge(node1, cost)); |
| 43 | + } |
| 44 | + } |
| 45 | +
|
| 46 | + private static int BFS() { |
| 47 | + Queue<int[]> q = new ArrayDeque<>(); |
| 48 | + visited[start] = true; |
| 49 | + int result = 0; |
| 50 | + // node, cost, max |
| 51 | + q.add(new int[]{start, 0, 0}); |
| 52 | +
|
| 53 | + while (!q.isEmpty()) { |
| 54 | + int[] current = q.poll(); |
| 55 | +
|
| 56 | + if (current[0] == end) { |
| 57 | + result = current[1]-current[2]; |
| 58 | + break; |
| 59 | + } |
| 60 | +
|
| 61 | + for (Edge edge : edges[current[0]]) { |
| 62 | + if (visited[edge.dest]) continue; |
| 63 | + visited[edge.dest] = true; |
| 64 | + int cost = current[1] + edge.cost; |
| 65 | + int max = Math.max(current[2], edge.cost); |
| 66 | + q.add(new int[]{edge.dest, cost, max}); |
| 67 | + } |
| 68 | + } |
| 69 | +
|
| 70 | + return result; |
| 71 | + } |
| 72 | +
|
| 73 | + static class Edge { |
| 74 | + int dest; |
| 75 | + int cost; |
| 76 | +
|
| 77 | + public Edge(int dest, int cost) { |
| 78 | + this.dest = dest; |
| 79 | + this.cost = cost; |
| 80 | + } |
| 81 | + } |
| 82 | +} |
| 83 | +``` |
0 commit comments