P3390 Solution
OIerWu_829 · · 题解
题目传送门
我妈呀我竟然还没写过这题
才看见这题开了题解区,那就一起来复习一下吧。
关于矩阵乘法,题目中已经说的很清楚了,我们只需要记住这个关键的式子即可:
但是,这样直接把矩阵
我们先拿普通的整数快速幂来举例。快速幂主要运用了分治法,即如果要计算
比如把
那么如何跳过那些没有的幂次呢?只需做一个判断,用位运算来实现,n & 1 是取出了 n >>= 1 是把
然后再根据取模的性质
#define int long long
// a^b % m
int Pow(int a, int b, int m)
{
a %= m; // 防止 a*a 越界
int res = 1;
while (b) // 把 b 看作二进制,逐个处理它的最后一位
{
if (b & 1) res = res * a % m; // 如果 n 的最后一位是 1,表示这个地方需要乘
a = a * a % mod; // 递推:a^2,a^4,a^8,a^16...
b >>= 1; // 把 b 右移一位,把刚处理过的 b 的最后一位去掉
}
return res;
}
再回到矩阵快速幂,只需把
#include <iostream>
#include <cstring>
#define int long long
using namespace std;
const int N = 105;
const int mod = 1e9 + 7;
int n, k;
struct Matrix { int m[N][N]; } a; // 矩阵
Matrix operator * (const Matrix& a, const Matrix& b) // 矩阵乘法
{
Matrix c;
memset(c.m, 0, sizeof c.m);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
for (int k = 0; k < n; k++)
c.m[i][j] = (c.m[i][j] + a.m[i][k] * b.m[k][j]) % mod;
return c;
}
Matrix Pow(Matrix a, int k) // 矩阵快速幂
{
Matrix ans;
memset(ans.m, 0, sizeof ans.m);
for (int i = 0; i < n; i++)
ans.m[i][i] = 1;
while (k)
{
if (k & 1) ans = ans * a;
a = a * a;
k >>= 1;
}
return ans;
}
signed main()
{
ios::sync_with_stdio(false);
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n >> k;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> a.m[i][j];
if (k == 0) // 根据题目,A^0 是单位矩阵 I
{
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cout << (i == j) << " \n"[j == n - 1];
return 0;
}
Matrix res = Pow(a, k); // 计算快速幂
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cout << res.m[i][j] << " \n"[j == n - 1];
return 0;
}