結果

問題 No.778 クリスマスツリー
ユーザー htkbhtkb
提出日時 2019-01-06 14:40:00
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 1,439 bytes
コンパイル時間 93 ms
コンパイル使用メモリ 12,800 KB
実行使用メモリ 113,432 KB
最終ジャッジ日時 2024-05-03 03:12:15
合計ジャッジ時間 16,611 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 33 ms
11,008 KB
testcase_01 AC 32 ms
10,752 KB
testcase_02 AC 33 ms
11,136 KB
testcase_03 AC 32 ms
11,136 KB
testcase_04 AC 33 ms
11,008 KB
testcase_05 AC 32 ms
10,880 KB
testcase_06 AC 1,578 ms
113,432 KB
testcase_07 AC 1,303 ms
63,132 KB
testcase_08 TLE -
testcase_09 AC 1,859 ms
74,396 KB
testcase_10 AC 1,865 ms
74,516 KB
testcase_11 AC 1,863 ms
74,480 KB
testcase_12 AC 1,852 ms
73,800 KB
testcase_13 AC 1,449 ms
74,044 KB
testcase_14 AC 1,549 ms
113,432 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):
    import sys
    sys.setrecursionlimit(10**7)
    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


def solve():
    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)


if __name__ == "__main__":
    import threading
    threading.stack_size(10**9)
    thread = threading.Thread(target=solve)
    thread.start()
0