結果

問題 No.778 クリスマスツリー
ユーザー tentententen
提出日時 2021-01-28 16:29:09
言語 Java21
(openjdk 21)
結果
AC  
実行時間 1,199 ms / 2,000 ms
コード長 1,569 bytes
コンパイル時間 2,448 ms
コンパイル使用メモリ 72,568 KB
実行使用メモリ 127,784 KB
最終ジャッジ日時 2023-09-08 07:20:02
合計ジャッジ時間 13,210 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 122 ms
55,832 KB
testcase_01 AC 118 ms
56,004 KB
testcase_02 AC 118 ms
55,572 KB
testcase_03 AC 118 ms
56,004 KB
testcase_04 AC 122 ms
55,812 KB
testcase_05 AC 122 ms
55,920 KB
testcase_06 AC 905 ms
127,632 KB
testcase_07 AC 804 ms
78,408 KB
testcase_08 AC 1,199 ms
88,752 KB
testcase_09 AC 1,179 ms
80,232 KB
testcase_10 AC 1,135 ms
80,312 KB
testcase_11 AC 1,110 ms
80,660 KB
testcase_12 AC 1,095 ms
80,696 KB
testcase_13 AC 850 ms
81,004 KB
testcase_14 AC 934 ms
127,784 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
    static BinaryIndexedTree bit;
    static ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            graph.add(new ArrayList<>());
        }
        for (int i = 1; i < n; i++) {
            graph.get(sc.nextInt()).add(i);
        }
        bit = new BinaryIndexedTree(n + 1);
        System.out.println(search(0));
    }
    
    static long search(int idx) {
        long sum = bit.getSum(idx + 1);
        bit.add(idx + 1, 1);
        for (int x : graph.get(idx)) {
            sum += search(x);
        }
        bit.add(idx + 1, -1);
        return sum;
    }
}

class BinaryIndexedTree {
    int size;
    int[] tree;
    
    public BinaryIndexedTree(int size) {
        this.size = size;
        tree = new int[size];
    }
    
    public void add(int idx, int value) {
        int mask = 1;
        while (idx < size) {
            if ((idx & mask) != 0) {
                tree[idx] += value;
                idx += mask;
            }
            mask <<= 1;
        }
    }
    
    public int getSum(int from, int to) {
        return getSum(to) - getSum(from - 1);
    }
    
    public int getSum(int x) {
        int mask = 1;
        int ans = 0;
        while (x > 0) {
            if ((x & mask) != 0) {
                ans += tree[x];
                x -= mask;
            }
            mask <<= 1;
        }
        return ans;
    }
}
0