結果

問題 No.778 クリスマスツリー
ユーザー tentententen
提出日時 2021-01-28 16:27:54
言語 Java21
(openjdk 21)
結果
WA  
実行時間 -
コード長 1,567 bytes
コンパイル時間 5,021 ms
コンパイル使用メモリ 74,784 KB
実行使用メモリ 126,696 KB
最終ジャッジ日時 2023-09-08 07:18:45
合計ジャッジ時間 14,063 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 125 ms
55,896 KB
testcase_01 AC 125 ms
55,692 KB
testcase_02 AC 125 ms
55,808 KB
testcase_03 AC 131 ms
55,732 KB
testcase_04 AC 127 ms
55,448 KB
testcase_05 AC 127 ms
55,744 KB
testcase_06 AC 971 ms
126,696 KB
testcase_07 AC 825 ms
77,848 KB
testcase_08 WA -
testcase_09 AC 1,126 ms
80,352 KB
testcase_10 AC 1,140 ms
80,312 KB
testcase_11 AC 1,187 ms
80,348 KB
testcase_12 AC 1,096 ms
81,068 KB
testcase_13 AC 880 ms
81,476 KB
testcase_14 WA -
権限があれば一括ダウンロードができます

ソースコード

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 int search(int idx) {
        int 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