結果

問題 No.778 クリスマスツリー
ユーザー lllllll88938494lllllll88938494
提出日時 2023-05-15 21:58:23
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 849 ms / 2,000 ms
コード長 1,002 bytes
コンパイル時間 631 ms
コンパイル使用メモリ 86,900 KB
実行使用メモリ 376,188 KB
最終ジャッジ日時 2023-08-20 21:07:28
合計ジャッジ時間 5,667 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 59 ms
71,268 KB
testcase_01 AC 58 ms
71,120 KB
testcase_02 AC 58 ms
71,360 KB
testcase_03 AC 62 ms
71,204 KB
testcase_04 AC 61 ms
71,176 KB
testcase_05 AC 59 ms
70,988 KB
testcase_06 AC 597 ms
376,188 KB
testcase_07 AC 221 ms
143,716 KB
testcase_08 AC 849 ms
231,804 KB
testcase_09 AC 446 ms
133,316 KB
testcase_10 AC 438 ms
132,560 KB
testcase_11 AC 425 ms
132,520 KB
testcase_12 AC 384 ms
132,356 KB
testcase_13 AC 254 ms
132,064 KB
testcase_14 AC 525 ms
313,976 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
 
    def _add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
            
    def _sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
        
n=int(input())
rin=[[] for i in range(n)]
a=list(map(int,input().split()))

for i in range(1,n):
    rin[a[i-1]].append(i)
    rin[i].append(a[i-1])

bit=Bit(n+2)

import sys
sys.setrecursionlimit(10**6)
kukan = [[0,0] for i in range(n)]
ind=1
def  cal(x,pre):
    global ind
    kukan[x][0] = ind
    if len(rin[x]) == 1 and x!= pre:
        kukan[x][1] = ind
        ind += 1
        return
    ind += 1
    for i in rin[x]:
        if i != pre:
            cal(i,x)
    
    kukan[x][1] = ind-1

cal(0,0)
ans = 0
for x in range(n-1,-1,-1):
    l,r=kukan[x][0],kukan[x][1]
    ans += bit._sum(r) - bit._sum(l-1)
    bit._add(l,1)


print(ans)
0