Home 백준 - 10830 행렬 제곱
Post
Cancel

백준 - 10830 행렬 제곱

문제

10830 행렬 제곱

screencapture

kotlin code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
fun main() {
    q10830()
}

fun q10830() {
    val mod = 1000
    val line = readln().split(" ").filter { it.isNotBlank() }
    val rowColumnCount = line.first().toInt()
    val multiplier = line.last().toLong()
    val matrix = readMatrix(rowColumnCount, rowColumnCount)

    val result = getPowerMatrixModP(matrix, multiplier, mod)

    result.printMatrix()
}

private fun readMatrix(rowCount:Int, columnCount:Int): Array<IntArray> {
    val matrix1 = Array(rowCount) { IntArray(columnCount) }
    for (m in matrix1) {
        val inputRow = readln().split(" ").map { it.toInt() }
        for (i in m.indices) {
            m[i] = inputRow[i]
        }
    }
    return matrix1
}

fun getPowerMatrixModP(matrix: Array<IntArray>, multiplier: Long, mod: Int): Array<IntArray> = when {
    multiplier == 1L -> matrix % mod
    multiplier.isOdd() -> {
        val half = getPowerMatrixModP(matrix, multiplier / 2, mod)
        half * half % mod
    }
    else -> getPowerMatrixModP(matrix, multiplier-1, mod) * matrix % mod
}

operator fun Array<IntArray>.rem(other: Int): Array<IntArray> {
    return Array(this.size) { y -> IntArray(this[y].size) { x -> this[y][x] % other  }}
}

operator fun Array<IntArray>.times(other: Array<IntArray>): Array<IntArray> {
    return Array(this.size){ y -> IntArray(other.first().size) { x -> this[y] * other.map { it[x] }.toIntArray() } }
}

operator fun IntArray.times(other: IntArray): Int {
    return this.mapIndexed { i, it -> other[i] * it }.toIntArray().sum()
}

private fun Long.isOdd(): Boolean {
    return this % 2 == 0L
}

fun Array<IntArray>.printMatrix() {
    this.forEach { row -> row.forEach { column -> print("$column ") }
        println()
    }
}
This post is licensed under CC BY 4.0 by the author.

백준 - 24480 알고리즘 수업 - 깊이 우선 탐색 2

백준 - 6549 히스토그램에서 가장 큰 직사각형 풀이