結果

問題 No.1817 Reversed Edges
コンテスト
ユーザー yudedako
提出日時 2022-01-25 18:03:56
言語 Scala(Beta)
(3.8.1)
コンパイル:
scalac _filename_
実行:
java -cp .:/home/linuxbrew/.linuxbrew/Cellar/scala/3.8.1/libexec/maven2/org/scala-lang/scala3-library_3/3.8.1/scala3-library_3-3.8.1.jar:/home/linuxbrew/.linuxbrew/Cellar/scala/3.8.1/libexec/maven2/org/scala-lang/scala-library/3.8.1/scala-library-3.8.1.jar _class_
結果
AC  
実行時間 1,425 ms / 2,000 ms
コード長 1,365 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 12,020 ms
コンパイル使用メモリ 293,272 KB
実行使用メモリ 82,644 KB
最終ジャッジ日時 2026-03-09 19:29:27
合計ジャッジ時間 41,790 ms
ジャッジサーバーID
(参考情報)
judge1_0 / judge2_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 23
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

import scala.collection.mutable
import scala.io.StdIn.*
import scala.math.{min, max}
@main def main =
  val n = readLine().toInt
  val edges = Array.fill(n - 1){
    val Array(u, v) = readLine().trim().split(' ').map(_.toInt - 1)
    (min(u, v), max(u, v))
  }
  val graph = Array.fill(n){Nil: List[Int]}
  for (u, v) <- edges do
    graph(u) ::= v
    graph(v) ::= u
  val depth = Array.fill(graph.length){-1}
  depth(0) = 0
  val parent = Array.fill(graph.length){-1}
  val queue = mutable.Queue(0)
  while queue.nonEmpty do
    val current = queue.dequeue()
    for next <- graph(current) do
      if depth(next) == -1 then
        depth(next) = depth(current) + 1
        queue.append(next)
        parent(next) = current
  var currentSum = edges.count((u, v) => depth(u) > depth(v))
  val stack = mutable.Stack(0)
  val result = Array.fill(n){-1}
  val state = graph.clone()
  while stack.nonEmpty do
    val current = stack.pop()
    state(current) match
      case Nil =>
        result(current) = currentSum
        if parent(current) >= 0 then
          currentSum += (if current > parent(current) then -1 else 1)
      case next::t =>
        stack.push(current)
        state(current) = t
        if depth(current) < depth(next) then
          currentSum += (if current > next then -1 else 1)
          stack.push(next)
  println(result.mkString("\n"))
0