結果

問題 No.1813 Magical Stones
ユーザー yudedako
提出日時 2022-01-30 23:42:14
言語 Scala(Beta)
(3.6.2)
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 2,449 bytes
コンパイル時間 14,321 ms
コンパイル使用メモリ 265,512 KB
実行使用メモリ 103,728 KB
最終ジャッジ日時 2024-06-11 08:31:09
合計ジャッジ時間 92,782 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 25 TLE * 15
権限があれば一括ダウンロードができます

ソースコード

diff #

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn.*
import scala.math.*
import scala.util.chaining.*
object DAG:
  def dag(graph: Array[ArrayBuffer[Int]]): Array[Int] =
    val n = graph.length
    val indices = Array.fill(n){0}
    val stack = Array.fill(n){0}
    val size = Array.fill(n){0}
    var pos = 0
    var outPos = n - 1
    for i <- 0 until n do
      if indices(i) == 0 then
        stack(pos) = i
        pos += 1
        while pos > 0 do
          pos -= 1
          val top = stack(pos)
          val edge = graph(top)
          if indices(top) == edge.size then
            indices(top) = -1
            stack(outPos) = top
            outPos -= 1
          else
            var index = indices(top)
            while index < edge.length && indices(edge(index)) != 0 do
              size(edge(index)) += 1
              index += 1
            pos += 1
            if index < edge.size then
              stack(pos) = edge(index)
              pos += 1
              size(edge(index)) += 1
              index += 1
            indices(top) = index
    val reverseGraph = Array.tabulate(n){i => Array.fill(size(i)){0}}
    for from <- graph.indices do
      for to <- graph(from) do
        size(to) -= 1
        reverseGraph(to)(size(to)) = from
    val newStack = size
    val result = indices
    for i <- stack do
      if result(i) < 0 then
        outPos += 1
        result(i) = outPos
        newStack(pos) = i
        pos += 1
        while pos > 0 do
          pos -= 1
          val from = newStack(pos)
          for to <- reverseGraph(from) do
            if result(to) < 0 then
              result(to) = outPos
              size(pos) = to
              pos += 1
    result
@main def main =
  val Array(n, m) = readLine().split(' ').map(_.toInt)
  val edges = Array.fill(m){
    val Array(a, b) = readLine().split(' ').map(_.toInt - 1)
    a -> b
  }
  val graph = Array.fill(n){ArrayBuffer[Int]()}
  for (a, b) <- edges do
    graph(a).append(b)
  val dag = DAG.dag(graph)
  val inDegree = Array.fill(dag.max + 1){0}
  val outDegree = Array.fill(inDegree.length){0}
  for (i, j) <- edges do
    val a = dag(i)
    val b = dag(j)
    if a != b then
      outDegree(a) += 1
      inDegree(b) += 1
  val greatest = inDegree.count(_ == 0)
  val smallest = outDegree.count(_ == 0)
  if inDegree.length == 1 then
    println(0)
  else
    println(max(greatest, smallest))

0