結果

問題 No.778 クリスマスツリー
ユーザー ikdikd
提出日時 2018-12-25 13:52:42
言語 Nim
(2.0.2)
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 1,377 bytes
コンパイル時間 4,369 ms
コンパイル使用メモリ 72,180 KB
実行使用メモリ 37,220 KB
最終ジャッジ日時 2023-08-04 04:43:42
合計ジャッジ時間 8,209 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 2 ms
4,376 KB
testcase_04 AC 2 ms
4,376 KB
testcase_05 AC 2 ms
4,380 KB
testcase_06 TLE -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

import strutils, sequtils, algorithm

type SegmentTree = object
  n: int
  dat: seq[int]
proc init(sz: int): SegmentTree =
  var n = 1
  while n<sz: n*=2
  var dat = newSeqWith(n*2-1, 0)
  result = SegmentTree(n: n, dat: dat)
proc add(this: var SegmentTree, i, x: int) =
  var k = i+this.n-1
  this.dat[k]+=x
  while k>0:
    k = (k-1) div 2
    this.dat[k] = this.dat[k*2+1]+this.dat[k*2+2]
proc rsum(this: SegmentTree, ql, qr, i, il, ir: int): int =
  if qr<=il or ir<=ql:
    result = 0
  elif ql<=il and ir<=qr:
    result = this.dat[i]
  else:
    let m = (il+ir) div 2
    result = this.rsum(ql, qr, i*2+1, il, m)+this.rsum(ql, qr, i*2+2, m, ir)

proc f(g: seq[seq[int]], a: var seq[int], i: int) =
  a.add(i)
  for j in g[i]:
    f(g, a, j)
    a.add(i)

proc main() =
  let
    n = stdin.readLine.parseInt
    a = stdin.readLine.split.map(parseInt)
  var g = newSeqWith(n, newSeq[int]())
  for i in 0..<(n-1):
    g[a[i]].add(i+1)
  var eul = newSeq[int]()
  f(g, eul, 0)
  var
    pos_first = newSeqWith(n, -1)
    pos_last = newSeqWith(n, -1)
  for i, v in eul:
    if pos_first[v]<0:
      pos_first[v] = i
  for i, v in reversed(eul):
    if pos_last[v]<0:
      pos_last[v] = eul.len-i
  var
    tree = init(eul.len)
    ans = 0'i64
  for i in 1..n:
    ans+=tree.rsum(pos_first[n-i], pos_last[n-i], 0, 0, tree.n)
    tree.add(pos_first[n-i], 1)
  echo ans
main()
0