結果
問題 | No.1854 Limited Bubble Sort |
ユーザー |
|
提出日時 | 2022-03-14 00:17:47 |
言語 | Scala(Beta) (3.6.2) |
結果 |
AC
|
実行時間 | 1,104 ms / 2,000 ms |
コード長 | 1,965 bytes |
コンパイル時間 | 11,773 ms |
コンパイル使用メモリ | 269,760 KB |
実行使用メモリ | 67,268 KB |
最終ジャッジ日時 | 2024-09-19 08:01:27 |
合計ジャッジ時間 | 40,206 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 25 |
ソースコード
import java.io.PrintWriterimport scala.collection.mutable.*import scala.io.StdIn.*import scala.util.chaining.*import scala.math.*import scala.reflect.ClassTagimport scala.util.*import scala.annotation.tailrecimport scala.collection.mutabledef solve(permutation: Array[Int]): Option[ArrayBuffer[Int]] =if permutation.forall(permutation.indices.contains(_)) thenpermutation.indices.find(i => permutation(i) == i) matchcase 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))elseNonedef solveFlat(array: Array[Int]): ArrayBuffer[Int] =if array.isEmpty thenreturn ArrayBuffer.emptyval indices = Array.fill(array.length){0}val leftCount = Array.fill(array.length){0}for (a, i) <- array.zipWithIndex doindices(a) = ileftCount(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) thenleftCount(current(i + 1)) -= 1elseleftCount(current(i)) += 1val temp = current(i)current(i) = current(i + 1)current(i + 1) = tempindices(current(i)) = iindices(current(i + 1)) = i + 1result.addOne(i + 1)for i <- array.indices dofor j <- i until indices(i) doif current(j) != j + 1 && current(j + 1) == j + 2 && leftCount(j + 2) + 1 != j + 2 thenswap(j)for j <- indices(i) until i by -1 doswap(j - 1)result@main def main =val testCount = readLine().toIntfor testCase <- 1 to testCount doval n = readLine().toIntval permutation = readLine().split(' ').map(_.toInt - 1)solve(permutation) matchcase Some(result) =>println(result.size)println(result.mkString(" "))case None =>println(-1)