結果
問題 | No.778 クリスマスツリー |
ユーザー |
![]() |
提出日時 | 2025-03-31 17:36:30 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 358 ms / 2,000 ms |
コード長 | 1,375 bytes |
コンパイル時間 | 126 ms |
コンパイル使用メモリ | 82,684 KB |
実行使用メモリ | 135,660 KB |
最終ジャッジ日時 | 2025-03-31 17:37:08 |
合計ジャッジ時間 | 3,712 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 12 |
ソースコード
class FenwickTree:def __init__(self, size):self.n = sizeself.tree = [0] * (self.n + 2) # 1-based indexing, handle up to size+1def add(self, idx, delta):idx += 1 # Convert to 1-basedwhile idx <= self.n + 1:self.tree[idx] += deltaidx += idx & -idxdef sum_query(self, idx):res = 0idx += 1 # Convert to 1-basedif idx < 1:return 0while idx > 0:res += self.tree[idx]idx -= idx & -idxreturn resdef main():import sysinput = sys.stdin.read().split()ptr = 0N = int(input[ptr])ptr += 1A = list(map(int, input[ptr:ptr + N-1]))ptr += N-1children = [[] for _ in range(N)]for i in range(N-1):parent = A[i]child = i + 1children[parent].append(child)fenwick = FenwickTree(N)ans = 0stack = [(0, False)]while stack:node, visited = stack.pop()if not visited:current_sum = fenwick.sum_query(node - 1)ans += current_sumfenwick.add(node, 1)stack.append((node, True))for child in reversed(children[node]):stack.append((child, False))else:fenwick.add(node, -1)print(ans)if __name__ == '__main__':main()