結果

問題 No.778 クリスマスツリー
ユーザー maspymaspy
提出日時 2020-02-29 21:00:45
言語 Python3
(3.11.6 + numpy 1.26.0 + scipy 1.11.3)
結果
AC  
実行時間 1,603 ms / 2,000 ms
コード長 1,828 bytes
コンパイル時間 104 ms
コンパイル使用メモリ 10,860 KB
実行使用メモリ 60,700 KB
最終ジャッジ日時 2023-08-03 23:13:13
合計ジャッジ時間 14,289 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 16 ms
8,076 KB
testcase_01 AC 16 ms
8,080 KB
testcase_02 AC 16 ms
8,116 KB
testcase_03 AC 16 ms
8,196 KB
testcase_04 AC 16 ms
8,076 KB
testcase_05 AC 16 ms
8,112 KB
testcase_06 AC 1,235 ms
60,700 KB
testcase_07 AC 1,122 ms
41,696 KB
testcase_08 AC 1,603 ms
58,308 KB
testcase_09 AC 1,483 ms
58,604 KB
testcase_10 AC 1,474 ms
58,580 KB
testcase_11 AC 1,465 ms
58,768 KB
testcase_12 AC 1,432 ms
58,604 KB
testcase_13 AC 1,173 ms
53,836 KB
testcase_14 AC 1,194 ms
58,372 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/env python3
# %%
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines


# %%
N, *A = map(int, read().split())

# %%
graph = [[] for _ in range(N + 1)]
for i, x in enumerate(A, 2):
    x += 1
    graph[i].append(x)
    graph[x].append(i)


# %%
class BinaryIndexedTree():
    def __init__(self, seq):
        self.size = len(seq)
        self.depth = self.size.bit_length()
        self.build(seq)

    def build(self, seq):
        data = seq
        size = self.size
        for i, x in enumerate(data):
            j = i + (i & (-i))
            if j < size:
                data[j] += data[i]
        self.data = data

    def __repr__(self):
        return self.data.__repr__()

    def get_sum(self, i):
        data = self.data
        s = 0
        while i:
            s += data[i]
            i -= i & -i
        return s

    def add(self, i, x):
        data = self.data
        size = self.size
        while i < size:
            data[i] += x
            i += i & -i

    def find_kth_element(self, k):
        data = self.data
        size = self.size
        x, sx = 0, 0
        dx = 1 << (self.depth)
        for i in range(self.depth - 1, -1, -1):
            dx = (1 << i)
            if x + dx >= size:
                continue
            y = x + dx
            sy = sx + data[y]
            if sy < k:
                x, sx = y, sy
        return x + 1


# # %%
par = [0] * (N + 1)
st = [1]
answer = 0
bit = BinaryIndexedTree([0] * (N + 1))
get_sum = bit.get_sum
add = bit.add
while st:
    x = st[-1]
    if not graph[x]:
        answer += get_sum(x)
        add(x, -1)
        st.pop()
        continue
    y = graph[x].pop()
    if y == par[x]:
        continue
    par[y] = x
    add(y, 1)
    st.append(y)


# %%
print(answer)
0