結果

問題 No.778 クリスマスツリー
ユーザー htkbhtkb
提出日時 2019-01-06 14:28:02
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
RE  
実行時間 -
コード長 1,260 bytes
コンパイル時間 312 ms
コンパイル使用メモリ 12,672 KB
実行使用メモリ 73,888 KB
最終ジャッジ日時 2024-05-03 03:11:13
合計ジャッジ時間 12,152 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 25 ms
10,880 KB
testcase_01 AC 26 ms
10,880 KB
testcase_02 AC 25 ms
10,752 KB
testcase_03 AC 27 ms
10,880 KB
testcase_04 AC 27 ms
10,752 KB
testcase_05 AC 26 ms
10,880 KB
testcase_06 RE -
testcase_07 AC 1,247 ms
62,384 KB
testcase_08 RE -
testcase_09 AC 1,687 ms
73,744 KB
testcase_10 AC 1,716 ms
73,888 KB
testcase_11 AC 1,694 ms
73,744 KB
testcase_12 AC 1,705 ms
73,644 KB
testcase_13 AC 1,351 ms
73,492 KB
testcase_14 RE -
権限があれば一括ダウンロードができます

ソースコード

diff #

class BinaryIndexedTree(object):
    __slots__ = ["tree"]

    def __init__(self, size: int):
        self.tree = [0]*(size+1)

    def add(self, index: int, value: int):
        tree = self.tree

        while index < len(tree):
            tree[index] += value
            index += index & -index

    def sum(self, index: int):
        tree, result = self.tree, 0

        while index:
            result += tree[index]
            index -= index & -index

        return result


def euler_tour(tree):
    edges = [[] for _ in [0]*(len(tree)+1)]
    for origin, destination in enumerate(tree, start=1):
        edges[destination].append(origin)

    subtree_range = [[0, 0] for _ in [0]*(len(tree)+1)]

    def rec(v, index):
        subtree_range[v][0] = index
        for destination in edges[v]:
            index = rec(destination, index+1)
        subtree_range[v][1] = index

        return index + 1

    rec(0, 1)
    return subtree_range


if __name__ == "__main__":
    N = int(input())
    tree = list(map(int, input().split()))
    subtree_range = euler_tour(tree)
    bit = BinaryIndexedTree(2*N-1)
    ans = 0

    for start, end in subtree_range[::-1]:
        ans += bit.sum(end) - bit.sum(start-1)
        bit.add(start, 1)

    print(ans)
0