結果
問題 | No.778 クリスマスツリー |
ユーザー |
👑 |
提出日時 | 2022-11-02 16:10:09 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 355 ms / 2,000 ms |
コード長 | 1,615 bytes |
コンパイル時間 | 209 ms |
コンパイル使用メモリ | 82,280 KB |
実行使用メモリ | 136,440 KB |
最終ジャッジ日時 | 2024-07-17 05:18:49 |
合計ジャッジ時間 | 4,755 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 12 |
ソースコード
class Bit:def __init__(self, n):self.size = nself.n0 = 1 << (n.bit_length() - 1)self.tree = [0] * (n + 1)def range_sum(self, l, r):return self.sum(r - 1) - self.sum(l - 1)def sum(self, i):i += 1s = 0while i > 0:s += self.tree[i]i -= i & -ireturn sdef get(self, i):return self.sum(i) - self.sum(i - 1)def add(self, i, x):i += 1while i <= self.size:self.tree[i] += xi += i & -idef lower_bound(self, x):pos = 0plus = self.n0while plus > 0:if pos + plus <= self.size and self.tree[pos + plus] < x:x -= self.tree[pos + plus]pos += plusplus //= 2return posdef EulerTour(n, edges, root=0):L = [-1] * nR = [0] * nstack = [(root, 1), (root, 0)]ind = 0while stack:pos, t = stack.pop()if t == 0:L[pos] = indind += 1for npos in edges[pos]:if L[npos] != -1:continuestack.append((npos, 1))stack.append((npos, 0))else:R[pos] = indreturn L, Rn = int(input())A = list(map(int, input().split()))edges = [[] for _ in range(n)]for i, p in enumerate(A, 1):edges[p].append(i)L, R = EulerTour(n, edges)bit = Bit(n)ans = 0for i in range(n - 1, -1, -1):ans += bit.range_sum(L[i], R[i])bit.add(L[i], 1)print(ans)