結果

問題 No.778 クリスマスツリー
ユーザー noriocnorioc
提出日時 2023-08-29 04:18:39
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 996 ms / 2,000 ms
コード長 1,566 bytes
コンパイル時間 314 ms
コンパイル使用メモリ 87,080 KB
実行使用メモリ 392,560 KB
最終ジャッジ日時 2023-08-29 04:18:51
合計ジャッジ時間 7,606 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 100 ms
71,600 KB
testcase_01 AC 92 ms
71,608 KB
testcase_02 AC 89 ms
71,744 KB
testcase_03 AC 92 ms
71,208 KB
testcase_04 AC 90 ms
71,524 KB
testcase_05 AC 91 ms
71,592 KB
testcase_06 AC 821 ms
392,120 KB
testcase_07 AC 296 ms
191,892 KB
testcase_08 AC 996 ms
239,696 KB
testcase_09 AC 542 ms
139,440 KB
testcase_10 AC 547 ms
138,316 KB
testcase_11 AC 578 ms
137,900 KB
testcase_12 AC 604 ms
140,224 KB
testcase_13 AC 497 ms
142,916 KB
testcase_14 AC 790 ms
392,560 KB
権限があれば一括ダウンロードができます

ソースコード

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(len(et.tour) + 10)
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