結果

問題 No.3113 The farthest point
ユーザー ks2m
提出日時 2025-04-18 21:00:16
言語 Java
(openjdk 23)
結果
AC  
実行時間 1,223 ms / 2,000 ms
コード長 1,329 bytes
コンパイル時間 2,847 ms
コンパイル使用メモリ 82,156 KB
実行使用メモリ 90,556 KB
最終ジャッジ日時 2025-04-18 21:00:44
合計ジャッジ時間 24,919 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
	static List<List<Hen>> list;
	static long ans;

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] sa = br.readLine().split(" ");
		int n = Integer.parseInt(sa[0]);
		int m = n - 1;
		list = new ArrayList<>(n);
		for (int i = 0; i < n; i++) {
			list.add(new ArrayList<>());
		}
		for (int i = 0; i < m; i++) {
			sa = br.readLine().split(" ");
			int a = Integer.parseInt(sa[0]) - 1;
			int b = Integer.parseInt(sa[1]) - 1;
			int c = Integer.parseInt(sa[2]);

			list.get(a).add(new Hen(b, c));
			list.get(b).add(new Hen(a, c));
		}
		br.close();

		dfs(0, -1);
		System.out.println(ans);
	}

	static long dfs(int x, int p) {
		long ret = 0;
		PriorityQueue<Long> que = new PriorityQueue<>(Collections.reverseOrder());
		for (Hen h : list.get(x)) {
			if (h.v != p) {
				long res = dfs(h.v, x) + h.c;
				ret = Math.max(ret, res);
				que.add(res);
			}
		}
		long val = 0;
		for (int i = 0; i < 2; i++) {
			if (!que.isEmpty()) {
				val += Math.max(que.poll(), 0);
			}
		}
		ans = Math.max(ans, val);
		return ret;
	}

	static class Hen {
		int v, c;

		public Hen(int v, int c) {
			this.v = v;
			this.c = c;
		}
	}
}
0