結果

問題 No.1103 Directed Length Sum
コンテスト
ユーザー ks2m
提出日時 2020-07-03 21:48:11
言語 Java
(openjdk 25.0.2)
コンパイル:
javac -encoding UTF8 _filename_
実行:
java -ea -Xmx700m -Xss256M -DONLINE_JUDGE=true _class_
結果
TLE  
実行時間 -
コード長 1,094 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 1,880 ms
コンパイル使用メモリ 84,008 KB
実行使用メモリ 39,356 KB
最終ジャッジ日時 2026-04-06 00:45:57
合計ジャッジ時間 7,495 ms
ジャッジサーバーID
(参考情報)
judge3_0 / judge1_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other TLE * 1 -- * 21
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

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);
			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);
	}

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