結果

問題 No.778 クリスマスツリー
ユーザー 双六双六
提出日時 2020-07-27 01:15:06
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,040 ms / 2,000 ms
コード長 1,392 bytes
コンパイル時間 577 ms
コンパイル使用メモリ 86,808 KB
実行使用メモリ 377,844 KB
最終ジャッジ日時 2023-09-11 05:28:33
合計ジャッジ時間 9,594 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 97 ms
71,308 KB
testcase_01 AC 97 ms
71,588 KB
testcase_02 AC 97 ms
71,560 KB
testcase_03 AC 96 ms
71,380 KB
testcase_04 AC 96 ms
71,576 KB
testcase_05 AC 96 ms
71,320 KB
testcase_06 AC 861 ms
374,924 KB
testcase_07 AC 383 ms
129,736 KB
testcase_08 AC 1,040 ms
214,604 KB
testcase_09 AC 684 ms
135,156 KB
testcase_10 AC 685 ms
135,340 KB
testcase_11 AC 677 ms
135,272 KB
testcase_12 AC 740 ms
134,812 KB
testcase_13 AC 526 ms
135,364 KB
testcase_14 AC 801 ms
377,844 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class SegmentTree(object):
	#N:処理する区間の長さ
	def __init__(self, N):
		self.N0 = 2 ** (N - 1).bit_length()
		self.data = [0] * (2 * self.N0)

	#k番目の値をxに更新
	def update(self, k, x):
		k += self.N0 - 1
		self.data[k] = x
		while k > 0:
			k = (k - 1) // 2
			self.data[k] = self.data[2 * k + 1] + self.data[2 * k + 2]

	#区間[l, r]の和
	def query(self, l, r):
		L = l + self.N0; R = r + self.N0 + 1
		m = 0
		while L < R:
			if R & 1:
				R -= 1
				m += self.data[R - 1]
			if L & 1:
				m += self.data[L - 1]
				L += 1
			L >>= 1; R >>= 1

		return m

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

ans = 0
def DFS(G, Seg, node):
	Seg.update(node, 1)
	for i in G.graph[node]:
		# if visit[i] != 1:
		# 	visit[i] = 1
		DFS(G, Seg, i)
	global ans
	ans += Seg.query(0, node) - 1
	Seg.update(node, 0)


#処理内容
def main():
	N = int(input())
	A = getlist()
	Seg = SegmentTree(N + 1)
	G = Graph()
	for i in range(N - 1):
		G.add_edge(A[i], i + 1)

	# ans = 0
	DFS(G, Seg, 0)
	print(ans)


if __name__ == '__main__':
	main()
0