結果

問題 No.1854 Limited Bubble Sort
コンテスト
ユーザー yudedako
提出日時 2022-03-14 00:17:47
言語 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  
実行時間 733 ms / 2,000 ms
コード長 1,965 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 12,801 ms
コンパイル使用メモリ 274,608 KB
実行使用メモリ 68,352 KB
最終ジャッジ日時 2026-03-09 20:06:53
合計ジャッジ時間 30,312 ms
ジャッジサーバーID
(参考情報)
judge1_1 / judge2_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 25
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

import java.io.PrintWriter
import scala.collection.mutable.*
import scala.io.StdIn.*
import scala.util.chaining.*
import scala.math.*
import scala.reflect.ClassTag
import scala.util.*
import scala.annotation.tailrec
import scala.collection.mutable


def solve(permutation: Array[Int]): Option[ArrayBuffer[Int]] =
  if permutation.forall(permutation.indices.contains(_)) then
    permutation.indices.find(i => permutation(i) == i) match
      case Some(i) =>
        solve(permutation.slice(0, i)).flatMap(result => solve(permutation.slice(i + 1, permutation.length).map(_ - i - 1)).map(_.map(_ + i + 1) ++ result))
      case None  =>
        Some(solveFlat(permutation))
  else
    None

def solveFlat(array: Array[Int]): ArrayBuffer[Int] =
  if array.isEmpty then
    return ArrayBuffer.empty
  val indices = Array.fill(array.length){0}
  val leftCount = Array.fill(array.length){0}
  for (a, i) <- array.zipWithIndex do
    indices(a) = i
    leftCount(a) = (0 until i).count(j => array(j) < array(i))
  val result = ArrayBuffer[Int]()
  val current = array.clone()
  def swap(i: Int) =
    if current(i) < current(i + 1) then
      leftCount(current(i + 1)) -= 1
    else
      leftCount(current(i)) += 1
    val temp = current(i)
    current(i) = current(i + 1)
    current(i + 1) = temp
    indices(current(i)) = i
    indices(current(i + 1)) = i + 1
    result.addOne(i + 1)
  for i <- array.indices do
    for j <- i until indices(i) do
      if current(j) != j + 1 && current(j + 1) == j + 2 && leftCount(j + 2) + 1 != j + 2 then
        swap(j)
    for j <- indices(i) until i by -1 do
      swap(j - 1)
  result


@main def main =
  val testCount = readLine().toInt
  for testCase <- 1 to testCount do
    val n = readLine().toInt
    val permutation = readLine().split(' ').map(_.toInt - 1)
    solve(permutation) match
      case Some(result) =>
        println(result.size)
        println(result.mkString(" "))
      case None =>
        println(-1)
0