結果

問題 No.778 クリスマスツリー
ユーザー lam6er
提出日時 2025-03-31 17:36:30
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 358 ms / 2,000 ms
コード長 1,375 bytes
コンパイル時間 126 ms
コンパイル使用メモリ 82,684 KB
実行使用メモリ 135,660 KB
最終ジャッジ日時 2025-03-31 17:37:08
合計ジャッジ時間 3,712 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 12
権限があれば一括ダウンロードができます

ソースコード

diff #

class FenwickTree:
    def __init__(self, size):
        self.n = size
        self.tree = [0] * (self.n + 2)  # 1-based indexing, handle up to size+1

    def add(self, idx, delta):
        idx += 1  # Convert to 1-based
        while idx <= self.n + 1:
            self.tree[idx] += delta
            idx += idx & -idx

    def sum_query(self, idx):
        res = 0
        idx += 1  # Convert to 1-based
        if idx < 1:
            return 0
        while idx > 0:
            res += self.tree[idx]
            idx -= idx & -idx
        return res

def main():
    import sys
    input = sys.stdin.read().split()
    ptr = 0
    N = int(input[ptr])
    ptr += 1
    A = list(map(int, input[ptr:ptr + N-1]))
    ptr += N-1

    children = [[] for _ in range(N)]
    for i in range(N-1):
        parent = A[i]
        child = i + 1
        children[parent].append(child)

    fenwick = FenwickTree(N)
    ans = 0
    stack = [(0, False)]

    while stack:
        node, visited = stack.pop()
        if not visited:
            current_sum = fenwick.sum_query(node - 1)
            ans += current_sum
            fenwick.add(node, 1)
            stack.append((node, True))
            for child in reversed(children[node]):
                stack.append((child, False))
        else:
            fenwick.add(node, -1)

    print(ans)

if __name__ == '__main__':
    main()
0