結果

問題 No.1103 Directed Length Sum
ユーザー ks2mks2m
提出日時 2020-07-03 21:57:04
言語 Java21
(openjdk 21)
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 1,151 bytes
コンパイル時間 3,666 ms
コンパイル使用メモリ 78,428 KB
実行使用メモリ 270,144 KB
最終ジャッジ日時 2023-10-17 02:09:01
合計ジャッジ時間 7,819 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 52 ms
57,924 KB
testcase_01 AC 51 ms
53,540 KB
testcase_02 TLE -
testcase_03 -- -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

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

public class Main {
	static int n;
	static List<List<Integer>> list;
	static long ans = 0;

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

		int root = 0;
		for (int i = 0; i < in.length; i++) {
			if (!in[i]) {
				root = i;
				break;
			}
		}
		dfs(root, -1, 1);
		System.out.println(ans % 1000000007);
	}

	static long dfs(int x, int p, long size) {
		long cnt = 0;
		for (int next : list.get(x)) {
			if (next != p) {
				cnt += dfs(next, x, size + 1);
			}
		}
		ans += cnt * size;
		return cnt + 1;
	}
}
0