結果

問題 No.1098 LCAs
ユーザー tenten
提出日時 2021-03-12 18:27:59
言語 Java
(openjdk 23)
結果
TLE  
実行時間 -
コード長 1,458 bytes
コンパイル時間 2,602 ms
コンパイル使用メモリ 78,768 KB
実行使用メモリ 104,456 KB
最終ジャッジ日時 2024-10-14 07:47:52
合計ジャッジ時間 14,533 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 20 TLE * 1 -- * 7
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;
import java.io.*;

public class Main {
    static ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
    static long[] ans;
	public static void main (String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		for (int i = 0; i < n; i++) {
		    graph.add(new ArrayList<>());
		}
		for (int i = 0; i < n - 1; i++) {
		    String[] line = br.readLine().split(" ", 2);
		    int a = Integer.parseInt(line[0]) - 1;
		    int b = Integer.parseInt(line[1]) - 1;
		    graph.get(a).add(b);
		    graph.get(b).add(a);
		}
		ans = new long[n];
		getChildren(0, 0);
		StringBuilder sb = new StringBuilder();
		for (long x : ans) {
		    sb.append(x).append("\n");
		}
        System.out.print(sb);
   }
   
   static int getChildren(int idx, int parent) {
       long count = 1;
       ArrayList<Integer> unders = new ArrayList<>();
       for (int x : graph.get(idx)) {
           if (x == parent) {
               continue;
           }
           int y = getChildren(x, idx);
           unders.add(y);
           count += y;
           ans[idx] += y * 2;
       }
       for (int i = 0; i < unders.size() - 1; i++) {
           for (int j = i + 1; j < unders.size(); j++) {
               int x = unders.get(i);
               ans[idx] += (long)x * unders.get(j) * 2;
           }
       }
       ans[idx]++;
       return (int)count;
   }
}

0