Posts 10830 행렬제곱
Post
Cancel

10830 행렬제곱

10830 행렬제곱

알고리즘 (거듭제곱, 행렬곱)

1
1. 그냥 행렬 거듭제곱으로 풀면됨

주의점

1
2
1. 입력의 B를 long long으로 받아야한다
2. AB = A 가 나오도록 하는 B행렬은 대각선이 모두 1이고 나머지는 0인 행렬이다

코드

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
58
59
60
61
#include <iostream>
#include <cstring>
using namespace std;

long long N, B;
long long map[5][5], result[5][5] = { {1,0,0,0,0}, {0,1,0,0,0}, {0,0,1,0,0}, {0,0,0,1,0}, {0,0,0,0,1} };

void multiMap(bool isResult);
void powerMap();

int main() {
	cin >> N >> B;
	for (int i = 0; i < N; i++)
		for (int j = 0; j < N; j++)
			cin >> map[i][j];

	powerMap();
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < N; j++)
			cout << result[i][j] << " ";
		cout << endl;
	}
}

void powerMap() {
	while (B >= 1) {
		if (B % 2 == 1) {
			multiMap(true);
			if (B == 1)
				break;
		}
		multiMap(false);
		B /= 2;
	}
}

void multiMap(bool isResult) {
	long long temp[5][5];
	memset(temp, 0, sizeof(temp));

	if (isResult) {
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				for (int k = 0; k < N; k++)
					temp[i][j] = ((temp[i][j] % 1000)+ ((result[i][k] * map[k][j]) % 1000));
				temp[i][j] %= 1000;
			}
		}
		memcpy(result, temp, sizeof(temp));
	}
	else {
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				for (int k = 0; k < N; k++)
					temp[i][j] = ((temp[i][j] % 1000) + ((map[i][k] * map[k][j]) % 1000));
				temp[i][j] %= 1000;
			}
		}
		memcpy(map, temp, sizeof(temp));
	}
}
This post is licensed under CC BY 4.0 by the author.

10775 airport

10942 Palindrome

Comments powered by Disqus.