๋ฐฑ์ค€ 10830 ํŒŒ์ด์ฌ

2021. 12. 26. 10:20ใ†๐Ÿ”ฑ Algorithm/Else

 

 

10830๋ฒˆ: ํ–‰๋ ฌ ์ œ๊ณฑ

ํฌ๊ธฐ๊ฐ€ N*N์ธ ํ–‰๋ ฌ A๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ด๋•Œ, A์˜ B์ œ๊ณฑ์„ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ์ˆ˜๊ฐ€ ๋งค์šฐ ์ปค์งˆ ์ˆ˜ ์žˆ์œผ๋‹ˆ, A^B์˜ ๊ฐ ์›์†Œ๋ฅผ 1,000์œผ๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

www.acmicpc.net

 

ํ’€์ง€ ๋ชปํ•œ ์ด์œ 

1. ํ–‰๋ ฌ ๊ณฑ์„ ์ฝ”๋“œ๋กœ ํ’€์–ด๋‚ด์ง€ ๋ชปํ•จ. 

2. ์žฌ๊ท€๋ฅผ ์ ์ ˆํžˆ ํ™œ์šฉํ•˜์ง€ ๋ชปํ•จ

3. ์žฌ๊ท€ ํƒˆ์ถœ ์กฐ๊ฑด ๋งŒ์ด๋ผ๋„ ์•Œ์•˜๋‹ค๋ฉด ํ’€์ด์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ์—ˆ์Œ

4. ๋งˆ์ง€๋ง‰ ์กฐ๊ฑด (1000 ์ดํ•˜) ์— ์ ์ ˆํžˆ ๋Œ€์ฒ˜ํ•˜์ง€ ๋ชปํ•จ.

 


ํ’€์ด 

์ด ๋ฌธ์ œ์˜ ํ•ต์‹ฌ์€ DP ๋ผ๊ณ  ํ•˜๋Š”๋ฐ, ์‚ฌ์‹ค ํ–‰๋ ฌ์˜ ๊ณฑ์…ˆ์„ ์ฝ”๋“œ๋กœ ํ’€์–ด๋‚ด๋Š” ๊ฒƒ ์—ญ์‹œ ํ•ต์‹ฌ์ด๋ผ๊ณ  ์ƒ๊ฐํ•œ๋‹ค.

ํ–‰๋ ฌ์˜ ๊ณฑ์…ˆ์€ ์ด๋Ÿฐ์‹์œผ๋กœ ์ง„ํ–‰๋œ๋‹ค. (1, 3) x (3, 1) ์ฒ˜๋Ÿผ ์•ž ํ–‰๋ ฌ์˜ ๋‘๋ฒˆ์งธ ์ขŒํ‘œ(3) ์™€ ๋’ท ํ–‰๋ ฌ์˜ ์ฒซ๋ฒˆ์งธ ์ขŒํ‘œ(3) ๊ฐ€ ๊ฐ™์•„์•ผ ํ–‰๋ ฌ์˜ ๊ณฑ์ด ์ด๋ฃจ์–ด์ง„๋‹ค. 10๋…„์ „ ์ค‘ํ•™๊ต ์ˆ˜ํ•™๊ณผ์ •์—์„œ ๋ฐฐ์šด ๊ธฐ์–ต์ด ๋‚œ๋‹ค.

์ด๋ฅผ ์ฝ”๋“œ๋กœ ํ’€์–ด๋‚ผ ๋•Œ๋„ ์ด ์›๋ฆฌ๋ฅผ ์ ์šฉํ•˜๋Š”๊ฒŒ ์ค‘์š”ํ•˜๋‹ค.

def matrix_mul(mat_a, mat_b):
    length = len(mat_a)
    temp = [[0] * length for _ in range(length)]
    for i in range(length):
        for j in range(length):
            for k in range(length):
                temp[i][j] += mat_a[i][k] * mat_b[k][j]
    return temp

์—ฌ๊ธฐ์„œ temp ๋ผ๋Š” ์›์†Œ๊ฐ€ ๋ชจ๋‘ 0์ธ ์ž„์‹œ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•œ๋‹ค. temp ๋Š” ๊ฐ ํ–‰๋ ฌ์˜ ๊ณฑ์…ˆ์˜ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํ„ดํ•˜๊ณ , ๋งค๋ฒˆ matrix_mul() ์ด ํ˜ธ์ถœ๋  ๋•Œ๋งˆ๋‹ค ์ดˆ๊ธฐํ™” ๋œ๋‹ค. ์ฆ‰ ๋™์ผ ํ–‰๋ ฌ์˜ ์ œ๊ณฑ์„ temp ๋ผ๋Š” ์ด๋ฆ„์œผ๋กœ ๋ฆฌํ„ดํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

 

 

 

 

์ฝ”๋“œ

import sys


def matrix_mul(mat_a, mat_b):
    length = len(mat_a)
    temp = [[0] * length for _ in range(length)]
    for i in range(length):
        for j in range(length):
            for k in range(length):
                temp[i][j] += mat_a[i][k] * mat_b[k][j]
            temp[i][j] %= 1000
    return temp


def matrix_pow(original, n):
    if n == 1:
        return original
    if n % 2 == 0:
        temp = matrix_pow(original, n // 2)
        return matrix_mul(temp, temp)
    else:
        temp = matrix_pow(original, n - 1)
        return matrix_mul(temp, original)


read = sys.stdin.readline
N, M = map(int, read().split())
matrix = [list(map(int, read().split())) for _ in range(N)]
result = matrix_pow(matrix, M)
for row in result:
    for num in row:
        print(num % 1000, end=' ')
    print()