結果

問題 No.872 All Tree Path
ユーザー yakamotoyakamoto
提出日時 2019-08-31 01:19:08
言語 Kotlin
(1.9.23)
結果
AC  
実行時間 1,225 ms / 3,000 ms
コード長 1,810 bytes
コンパイル時間 17,589 ms
コンパイル使用メモリ 464,272 KB
実行使用メモリ 115,188 KB
最終ジャッジ日時 2024-05-01 23:58:27
合計ジャッジ時間 34,541 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1,225 ms
115,080 KB
testcase_01 AC 1,196 ms
115,188 KB
testcase_02 AC 1,168 ms
114,992 KB
testcase_03 AC 906 ms
114,588 KB
testcase_04 AC 320 ms
51,804 KB
testcase_05 AC 1,154 ms
114,908 KB
testcase_06 AC 1,151 ms
114,936 KB
testcase_07 AC 1,204 ms
114,892 KB
testcase_08 AC 579 ms
69,828 KB
testcase_09 AC 570 ms
69,908 KB
testcase_10 AC 608 ms
69,484 KB
testcase_11 AC 583 ms
69,656 KB
testcase_12 AC 577 ms
69,392 KB
testcase_13 AC 331 ms
51,752 KB
testcase_14 AC 330 ms
51,976 KB
testcase_15 AC 334 ms
51,884 KB
testcase_16 AC 337 ms
51,692 KB
testcase_17 AC 332 ms
51,868 KB
testcase_18 AC 334 ms
51,868 KB
testcase_19 AC 334 ms
51,968 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import kotlin.math.max
import kotlin.math.min

// なんか本番でエラーでる
private val isDebug = runCatching {
  System.getenv("MY_DEBUG") != null
}.fold({it}, {false})

private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }.toIntArray()
private fun readLongs() = readStrings().map { it.toLong() }.toLongArray()
private fun debug(msg: () -> String) {
  if (isDebug) System.err.println(msg())
}
private fun debug(a: IntArray) {
  if (isDebug) debug{a.joinToString(" ")}
}

val MOD = 1000000007

data class Entry(val i: Int, val x: Long)

fun main() {
  val N = readInt()
  val g = Array<MutableList<Int>>(N){ mutableListOf()}
  val U = IntArray(N - 1)
  val V = IntArray(N - 1)
  val W = IntArray(N - 1)
  repeat(N - 1) {
    var (u, v, w) = readInts()
    u--; v--
    g[u].add(v)
    g[v].add(u)
    U[it] = u
    V[it] = v
    W[it] = w
  }
  val (p, q) = traceBfs(g)
  val dp = IntArray(N)
  for (i in N - 1 downTo 0) {
    val v = q[i]
    dp[v]++ // 自分
    for (u in g[v]) {
      if (u != p[v]) {
        dp[v] += dp[u]
      }
    }
  }
  debug(dp)
  debug(p)
  debug(q)

  var ans = 0L
  for (i in 0 until N - 1) {
    val cnt = if (p[U[i]] == V[i]) {
      dp[U[i]]
    } else {
      dp[V[i]]
    }
    ans += cnt.toLong() * (N - cnt) * W[i] * 2
  }

  println(ans)
}

/**
 * (parent, queue)
 */
fun traceBfs(g: Array<MutableList<Int>>, rt: Int = 0): Array<IntArray> {
  val n = g.size
  val q = IntArray(n)
  val p = IntArray(n){-2}
  var cur = 0
  var last = 1
  p[0] = -1
  q[0] = rt
  while (cur < last) {
    val v = q[cur++]
    for (u in g[v]) {
      if (p[u] == -2) {
        p[u] = v
        q[last++] = u
      }
    }
  }
  return arrayOf(p, q)
}
0