結果

問題 No.1103 Directed Length Sum
コンテスト
ユーザー tenten
提出日時 2020-08-18 08:36:08
言語 Java
(openjdk 25.0.2)
コンパイル:
javac -encoding UTF8 _filename_
実行:
java -ea -Xmx700m -Xss256M -DONLINE_JUDGE=true _class_
結果
AC  
実行時間 2,589 ms / 3,000 ms
コード長 1,087 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 1,848 ms
コンパイル使用メモリ 83,656 KB
実行使用メモリ 142,928 KB
最終ジャッジ日時 2026-04-28 07:48:08
合計ジャッジ時間 34,552 ms
ジャッジサーバーID
(参考情報)
judge3_0 / judge2_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 22
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

import java.util.*;

public class Main {
    static final int MOD = 1000000007;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        HashMap<Integer, Integer> graph = new HashMap<>();
        for (int i = 0; i < n - 1; i++) {
            int a = sc.nextInt() - 1;
            int b = sc.nextInt() - 1;
            graph.put(b, a);
        }
        int[] depth = new int[n];
        Arrays.fill(depth, -1);
        for (int i = 0; i < n; i++) {
            getDepth(i, graph, depth);
        }
        long ans = 0;
        for (int x : depth) {
            ans += (long)x * (x + 1) / 2 % MOD;
            ans %= MOD;
        }
        System.out.println(ans);
    }
    
    static int getDepth(int idx, HashMap<Integer, Integer> graph, int[] depth) {
        if (depth[idx] == -1) {
            if (graph.containsKey(idx))  {
                depth[idx] = getDepth(graph.get(idx), graph, depth) + 1;
            } else {
                depth[idx] = 0;
            }
        }
        return depth[idx];
    }
}
0