結果

問題 No.1103 Directed Length Sum
ユーザー tentententen
提出日時 2021-03-15 20:13:19
言語 Java21
(openjdk 21)
結果
TLE  
実行時間 -
コード長 1,478 bytes
コンパイル時間 3,197 ms
コンパイル使用メモリ 79,096 KB
実行使用メモリ 409,984 KB
最終ジャッジ日時 2024-04-24 22:56:40
合計ジャッジ時間 10,869 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 137 ms
46,668 KB
testcase_01 AC 133 ms
41,188 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.util.*;

public class Main {
    static ArrayList<ArrayList<Integer>> graphIn = new ArrayList<>();
    static ArrayList<ArrayList<Integer>> graphOut = new ArrayList<>();
    static int[] inCounts;
    static int[] outCounts;
    static final int MOD = 1000000007;
	public static void main (String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		for (int i = 0; i < n; i++) {
		    graphIn.add(new ArrayList<>());
		    graphOut.add(new ArrayList<>());
		}
		int[] ins = new int[n - 1];
		int[] outs = new int[n - 1];
		for (int i = 0; i < n - 1; i++) {
		    ins[i] = sc.nextInt() - 1;
		    outs[i] = sc.nextInt() - 1;
		    graphOut.get(ins[i]).add(outs[i]);
		    graphIn.get(outs[i]).add(ins[i]);
		}
		inCounts = new int[n];
		outCounts = new int[n];
		long ans = 0;
		for (int i = 0; i < n - 1; i++) {
		    ans += (long)getInCount(ins[i]) * getOutCount(outs[i]) % MOD;
		    ans %= MOD;
		}
		System.out.println(ans);
   }
   
   static int getInCount(int idx) {
       if (inCounts[idx] == 0) {
           inCounts[idx] = 1;
           for (int x : graphIn.get(idx)) {
               inCounts[idx] += getInCount(x);
           }
       }
       return inCounts[idx];
   }
   
   static int getOutCount(int idx) {
       if (outCounts[idx] == 0) {
           outCounts[idx] = 1;
           for (int x : graphOut.get(idx)) {
               outCounts[idx] += getOutCount(x);
           }
       }
       return outCounts[idx];
   }
}
0