1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

StringをCharにしたら処理速度が倍になった

Last updated at Posted at 2024-10-31

Stringを甘く見ていてめっちゃハマってしまったので戒めに残しておく
この問題 https://atcoder.jp/contests/abc375/tasks/abc375_c

解答コード

fun main(){
    val n = readln().toInt()
-    var pre: MutableList<List<String>> = mutableListOf()
-    var next: Array<Array<String>> = Array(n){Array(n){""}}
+    var pre: MutableList<List<Char>> = mutableListOf()
+    var next: Array<Array<Char>> = Array(n){Array(n){'.'}}
    repeat(n) {
        pre.add(
-            (readln().map { it.toString() })
+            (readln().toList())
        )
    }

    for(x in 1 .. n) {
        for (y in 1 .. n) {
            val convNum = minOf(x,y,n+1-x,n+1-y) % 4 // 変換回数
            var (i,j) = listOf(y, x)
            repeat(convNum) {
                val tmp = i
                i = n+1-j
                j = tmp
            }
            next[y-1][x-1] = pre[i-1][j-1]
        }
    }
    println(next.map{it.joinToString("")}.joinToString("\n"))
}

実行時間

TLE 3048ms
AC 1741ms

倍近い時間がかかっている!

学び

Javaの文字列は不変オブジェクトで、文字列の内容を変更するたびに新しいインスタンスが生成されるのでC/C++の感覚で扱うと痛い目を見るらしい1

StringがCharより重いという感覚は勿論あったが、そうはいっても文字数次第で大差ないだろうくらいの感覚だったのでアルゴリズムを疑い続けてめっちゃハマってしまった

  1. ChatGPT様ありがとう!!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?