|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static class Node { |
| 7 | + int to,cost; |
| 8 | + Node(int to, int cost) { |
| 9 | + this.to = to; |
| 10 | + this.cost = cost; |
| 11 | + } |
| 12 | + } |
| 13 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 14 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 15 | + static StringTokenizer st; |
| 16 | + static int N; |
| 17 | + static List<Node>[] adjList; |
| 18 | + |
| 19 | + public static void main(String[] args) throws Exception { |
| 20 | + N = Integer.parseInt(br.readLine()); |
| 21 | + if(N == 1){ |
| 22 | + bw.write("0"); |
| 23 | + bw.close(); |
| 24 | + return; |
| 25 | + } |
| 26 | + adjList = new ArrayList[N+1]; |
| 27 | + for (int i = 1; i <= N; i++) { |
| 28 | + adjList[i] = new ArrayList<>(); |
| 29 | + } |
| 30 | + for (int i = 1; i < N; i++) { |
| 31 | + st = new StringTokenizer(br.readLine()); |
| 32 | + int p = Integer.parseInt(st.nextToken()); |
| 33 | + int c = Integer.parseInt(st.nextToken()); |
| 34 | + int w = Integer.parseInt(st.nextToken()); |
| 35 | + adjList[p].add(new Node(c, w)); |
| 36 | + adjList[c].add(new Node(p, w)); |
| 37 | + } |
| 38 | + int[] dist = new int[N+1]; |
| 39 | + int A = BFS(1,dist); |
| 40 | + int B = BFS(A,dist); |
| 41 | + bw.write(dist[B]+""); |
| 42 | + bw.close(); |
| 43 | + } |
| 44 | + public static int BFS(int start,int[] dist){ |
| 45 | + Arrays.fill(dist, Integer.MAX_VALUE); |
| 46 | + Queue<Integer> q = new ArrayDeque<>(); |
| 47 | + q.add(start); |
| 48 | + dist[start] = 0; |
| 49 | + |
| 50 | + int destination = start; |
| 51 | + while(!q.isEmpty()){ |
| 52 | + int cur = q.poll(); |
| 53 | + for(Node node : adjList[cur]){ |
| 54 | + if(dist[node.to] == Integer.MAX_VALUE){ |
| 55 | + dist[node.to] = dist[cur] + node.cost; |
| 56 | + q.add(node.to); |
| 57 | + if(dist[node.to] > dist[destination]) destination = node.to; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + return destination; |
| 62 | + } |
| 63 | +} |
| 64 | +``` |
0 commit comments