結果

問題 No.872 All Tree Path
ユーザー ks2mks2m
提出日時 2019-08-30 22:16:20
言語 Java21
(openjdk 21)
結果
AC  
実行時間 1,018 ms / 3,000 ms
コード長 1,269 bytes
コンパイル時間 2,844 ms
コンパイル使用メモリ 79,184 KB
実行使用メモリ 107,244 KB
最終ジャッジ日時 2024-05-01 18:24:40
合計ジャッジ時間 12,717 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 922 ms
86,968 KB
testcase_01 AC 956 ms
87,716 KB
testcase_02 AC 934 ms
87,700 KB
testcase_03 AC 855 ms
107,244 KB
testcase_04 AC 55 ms
50,116 KB
testcase_05 AC 1,018 ms
87,804 KB
testcase_06 AC 905 ms
87,808 KB
testcase_07 AC 922 ms
89,560 KB
testcase_08 AC 201 ms
55,432 KB
testcase_09 AC 208 ms
55,476 KB
testcase_10 AC 195 ms
55,304 KB
testcase_11 AC 205 ms
55,564 KB
testcase_12 AC 202 ms
55,400 KB
testcase_13 AC 58 ms
50,012 KB
testcase_14 AC 57 ms
50,116 KB
testcase_15 AC 57 ms
49,964 KB
testcase_16 AC 56 ms
50,228 KB
testcase_17 AC 58 ms
50,404 KB
testcase_18 AC 57 ms
50,108 KB
testcase_19 AC 57 ms
49,872 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main {
	static Hen[] arr;
	static List<List<Hen>> list;

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		arr = new Hen[n - 1];
		list = new ArrayList<>(n);
		for (int i = 0; i < n; i++) {
			list.add(new ArrayList<>());
		}
		for (int i = 0; i < n - 1; i++) {
			String[] sa = br.readLine().split(" ");
			Hen h = new Hen();
			h.i = i;
			h.u = Integer.parseInt(sa[0]) - 1;
			h.v = Integer.parseInt(sa[1]) - 1;
			h.w = Integer.parseInt(sa[2]);
			arr[i] = h;
			list.get(h.u).add(h);
			list.get(h.v).add(h);
		}
		br.close();

		dfs(0, -1);

		long ans = 0;
		for (int i = 0; i < arr.length; i++) {
			ans += (long) arr[i].w * arr[i].c * (n - arr[i].c) * 2;
		}
		System.out.println(ans);
	}

	static class Hen {
		int i, u, v, w, c;
	}

	static int dfs(int x, int p) {
		List<Hen> nexts = list.get(x);
		int sum = 1;
		for (Hen h : nexts) {
			int next = h.u;
			if (next == x) {
				next = h.v;
			}
			if (next != p) {
				int c = dfs(next, x);
				h.c = c;
				sum += c;
			}
		}
		return sum;
	}
}
0