結果

問題 No.778 クリスマスツリー
ユーザー tcltktcltk
提出日時 2021-02-01 12:51:55
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 920 ms / 2,000 ms
コード長 1,582 bytes
コンパイル時間 280 ms
コンパイル使用メモリ 87,152 KB
実行使用メモリ 382,548 KB
最終ジャッジ日時 2023-09-12 10:07:55
合計ジャッジ時間 9,659 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 207 ms
81,528 KB
testcase_01 AC 203 ms
81,368 KB
testcase_02 AC 202 ms
81,616 KB
testcase_03 AC 201 ms
81,412 KB
testcase_04 AC 202 ms
81,592 KB
testcase_05 AC 206 ms
81,596 KB
testcase_06 AC 920 ms
380,952 KB
testcase_07 AC 374 ms
134,856 KB
testcase_08 AC 906 ms
213,828 KB
testcase_09 AC 571 ms
126,976 KB
testcase_10 AC 587 ms
127,064 KB
testcase_11 AC 577 ms
127,108 KB
testcase_12 AC 614 ms
126,764 KB
testcase_13 AC 455 ms
127,112 KB
testcase_14 AC 870 ms
382,548 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#region Header
#!/usr/bin/env python3
# from typing import *

import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq

def input():
    return sys.stdin.readline()[:-1]

sys.setrecursionlimit(1000000)
#endregion

# _INPUT = """3
# 2 0
# """
# sys.stdin = io.StringIO(_INPUT)

# 最もシンプル
class BIT:
    """
    Binary Indexed Tree (Fenwick Tree), 1-indexed
    """

    def __init__(self, n):
        """
        Parameters
        ----------
        n : int
            要素数。index は 0..n になる。
        """
        self.size = n
        self.data = [0] * (n+1)
        # self.depth = n.bit_length()

    def add(self, i, x):
        while i <= self.size:
            self.data[i] += x
            i += i & -i

    def get_sum(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & -i
        return s

    def get_rsum(self, l, r):
        """
        [l, r) の sum
        """
        return self.get_sum(r) - self.get_sum(l-1)

def dfs(G, bit, N, pos):

    n = bit.get_sum(pos+1)
    bit.add(pos+1, 1)

    for next_pos in G[pos]:
        n += dfs(G, bit, N, next_pos)

    bit.add(pos+1, -1)

    return n


def main():
    N = int(input())
    A = list(map(int, input().split()))

    G = [list() for _ in range(N)]
    for i in range(N-1):
        G[A[i]].append(i+1)

    bit = BIT(N)
    ans = dfs(G, bit, N, 0)
    print(ans)

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