結果

問題 No.778 クリスマスツリー
ユーザー noriocnorioc
提出日時 2023-08-29 04:16:36
言語 PyPy3
(7.3.15)
結果
RE  
実行時間 -
コード長 1,550 bytes
コンパイル時間 369 ms
コンパイル使用メモリ 87,184 KB
実行使用メモリ 395,272 KB
最終ジャッジ日時 2023-08-29 04:16:43
合計ジャッジ時間 7,357 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 91 ms
71,640 KB
testcase_01 AC 91 ms
71,232 KB
testcase_02 AC 92 ms
71,232 KB
testcase_03 AC 122 ms
71,560 KB
testcase_04 AC 93 ms
71,600 KB
testcase_05 AC 93 ms
71,584 KB
testcase_06 RE -
testcase_07 RE -
testcase_08 RE -
testcase_09 RE -
testcase_10 RE -
testcase_11 RE -
testcase_12 RE -
testcase_13 RE -
testcase_14 RE -
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict
import sys
sys.setrecursionlimit(10 ** 6)


class FenwickTree:
    def __init__(self, n):
        self.data = [0] * (n + 10)

    def add(self, p, x):
        assert 0 <= p
        p += 1
        while p < len(self.data):
            self.data[p] += x
            p += p & -p

    def sum(self, p):
        """区間 [0, p] の和"""
        assert 0 <= p
        p += 1
        s = 0
        while p > 0:
            s += self.data[p]
            p -= p & -p
        return s

    def rangesum(self, l, r):
        """区間 [l, r] の和"""
        assert 0 <= l <= r
        s = self.sum(r)
        if l > 0:
            s -= self.sum(l-1)
        return s


class EulerTour:
    def __init__(self, n: int, root: int, adj):
        tour = []  # オイラーツアー
        lt = [0] * n  # 各頂点番号に対する tour の最左/最右の位置
        rt = [0] * n

        def dfs(v, prev):
            lt[v] = len(tour)
            tour.append(v)
            for to in adj[v]:
                if to == prev: continue
                dfs(to, v)
                tour.append(v)
            rt[v] = len(tour) - 1

        dfs(root, -1)
        self.tour = tour
        self.lt = lt
        self.rt = rt


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

adj = defaultdict(list)
for i in range(N-1):
    par = A[i]
    adj[par].append(i+1)

ans = 0
et = EulerTour(N, 0, adj)
ft = FenwickTree(N)
for i in range(N-1, -1, -1):
    ans += ft.rangesum(et.lt[i], et.rt[i])
    ft.add(et.lt[i], 1)

print(ans)
0