結果

問題 No.778 クリスマスツリー
ユーザー noriocnorioc
提出日時 2024-04-17 00:24:45
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 880 ms / 2,000 ms
コード長 1,743 bytes
コンパイル時間 252 ms
コンパイル使用メモリ 82,596 KB
実行使用メモリ 363,384 KB
最終ジャッジ日時 2024-04-17 00:24:53
合計ジャッジ時間 6,918 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 40 ms
54,932 KB
testcase_01 AC 38 ms
54,692 KB
testcase_02 AC 39 ms
54,856 KB
testcase_03 AC 39 ms
54,796 KB
testcase_04 AC 39 ms
54,140 KB
testcase_05 AC 39 ms
54,688 KB
testcase_06 AC 763 ms
363,384 KB
testcase_07 AC 323 ms
152,192 KB
testcase_08 AC 880 ms
231,096 KB
testcase_09 AC 434 ms
131,572 KB
testcase_10 AC 453 ms
129,168 KB
testcase_11 AC 444 ms
132,224 KB
testcase_12 AC 492 ms
134,652 KB
testcase_13 AC 383 ms
135,236 KB
testcase_14 AC 710 ms
362,192 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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


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

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

    def sum(self, p):
        """区間 [0, p] の和"""
        assert 0 <= p < self.n
        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 < self.n
        s = self.sum(r)
        if l > 0:
            s -= self.sum(l-1)
        return s


class EulerTourVertex:
    def __init__(self, n, adj, root=0):
        vs = []  # 頂点 (訪問順)
        v_in = [0] * n   # 頂点の最初に通った時刻
        v_out = [0] * n  # 頂点の最後に通った時刻

        def dfs(v, par):
            vs.append(v)
            v_in[v] = len(vs)-1
            for to in adj[v]:
                if to == par: continue
                dfs(to, v)
                vs.append(v)

            v_out[v] = len(vs)-1

        dfs(root, -1)
        self.vs = vs
        self.v_in = v_in
        self.v_out = v_out


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)

et = EulerTourVertex(N, adj, root=0)
ft = FenwickTree(len(et.vs) + 10)
ans = 0
for i in reversed(range(N)):  # 頂点番号の大きい順
    # 部分木に、頂点 i よりも大きい頂点の個数をカウント
    ans += ft.rangesum(et.v_in[i], et.v_out[i])
    ft.add(et.v_in[i], 1)

print(ans)
0