結果
問題 | No.778 クリスマスツリー |
ユーザー |
![]() |
提出日時 | 2023-08-29 04:16:36 |
言語 | PyPy3 (7.3.15) |
結果 |
RE
|
実行時間 | - |
コード長 | 1,550 bytes |
コンパイル時間 | 723 ms |
コンパイル使用メモリ | 82,432 KB |
実行使用メモリ | 360,068 KB |
最終ジャッジ日時 | 2024-12-30 20:58:43 |
合計ジャッジ時間 | 7,050 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 3 RE * 9 |
ソースコード
from collections import defaultdictimport syssys.setrecursionlimit(10 ** 6)class FenwickTree:def __init__(self, n):self.data = [0] * (n + 10)def add(self, p, x):assert 0 <= pp += 1while p < len(self.data):self.data[p] += xp += p & -pdef sum(self, p):"""区間 [0, p] の和"""assert 0 <= pp += 1s = 0while p > 0:s += self.data[p]p -= p & -preturn sdef rangesum(self, l, r):"""区間 [l, r] の和"""assert 0 <= l <= rs = self.sum(r)if l > 0:s -= self.sum(l-1)return sclass EulerTour:def __init__(self, n: int, root: int, adj):tour = [] # オイラーツアーlt = [0] * n # 各頂点番号に対する tour の最左/最右の位置rt = [0] * ndef dfs(v, prev):lt[v] = len(tour)tour.append(v)for to in adj[v]:if to == prev: continuedfs(to, v)tour.append(v)rt[v] = len(tour) - 1dfs(root, -1)self.tour = tourself.lt = ltself.rt = rtN = 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 = 0et = 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)