結果

問題 No.778 クリスマスツリー
ユーザー htkbhtkb
提出日時 2019-01-06 15:33:04
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 437 ms / 2,000 ms
コード長 1,579 bytes
コンパイル時間 134 ms
コンパイル使用メモリ 82,316 KB
実行使用メモリ 130,608 KB
最終ジャッジ日時 2024-04-22 03:05:39
合計ジャッジ時間 4,062 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 34 ms
53,504 KB
testcase_01 AC 36 ms
53,888 KB
testcase_02 AC 37 ms
53,504 KB
testcase_03 AC 36 ms
54,016 KB
testcase_04 AC 36 ms
53,760 KB
testcase_05 AC 38 ms
53,888 KB
testcase_06 AC 247 ms
130,360 KB
testcase_07 AC 221 ms
124,192 KB
testcase_08 AC 437 ms
121,432 KB
testcase_09 AC 405 ms
118,828 KB
testcase_10 AC 418 ms
118,832 KB
testcase_11 AC 405 ms
118,908 KB
testcase_12 AC 407 ms
118,900 KB
testcase_13 AC 257 ms
119,012 KB
testcase_14 AC 249 ms
130,608 KB
権限があれば一括ダウンロードができます

ソースコード

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):
    from collections import deque

    tree_size, euler_tour_size = len(tree), len(tree)*2-1
    edges = [[] for _ in [0]*tree_size]
    for origin, destination in enumerate(tree):
        if destination >= 0:
            edges[destination].append(origin)

    subtree_range = [[0, 0] for _ in [0]*tree_size]
    dq, index = deque([0]), 0
    pop, extend = dq.pop, dq.extend

    while index < euler_tour_size:
        index, v = index+1, pop()
        if not subtree_range[v][0]:
            subtree_range[v][0] = index
        else:
            subtree_range[v][1] = index
            continue

        dq.append(tree[v])
        if edges[v]:
            dq.extend(edges[v])
        else:
            subtree_range[v][1] = index

    return subtree_range


if __name__ == "__main__":
    N = int(input())
    tree = [-1] + 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