题目连接
基准时间限制:3 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
收藏
关注
给出一个N * N的矩阵,其中的元素均为正整数。求这个矩阵的M次方。由于M次方的计算结果太大,只需要输出每个元素Mod (10^9 + 7)的结果。
Input
第1行:2个数N和M,中间用空格分隔。N为矩阵的大小,M为M次方。(2 <= N <= 100, 1 <= M <= 10^9)
第2 - N + 1行:每行N个数,对应N * N矩阵中的1行。(0 <= N[i] <= 10^9)
Output
共N行,每行N个数,对应M次方Mod (10^9 + 7)的结果。
Input示例
2 3
1 1
1 1
Output示例
4 4
4 4
这个题是用operator重载一下矩阵的乘法运算,然后按照快速幂的方法来求解
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
#define M 110
#define LL long long
#define MOD 1000000007
struct node
{
LL m[M][M];
} unit;
int n;
void init()//单位矩阵
{
for(int i=0; i<M; i++)
{
unit.m[i][i] = 1;
}
}
node operator * (node t1, node t2)//重载一下乘法
{
node res;
LL x;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
x = 0;
for(int k=0; k<n; k++)
{
x += (t1.m[i][k] * t2.m[k][j]) % MOD;
x %= MOD;
}
res.m[i][j] = x;
}
}
return res;
}
node quick_pow(node x, int m)
{
node res = unit;//单位矩阵
while(m)
{
if(m&1)
{
res = res * x;
}
x = x * x;
m >>= 1;
}
return res;
}
int main()
{
int m;
init();
node a = unit;
scanf("%d%d", &n, &m);
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
scanf("%d", &a.m[i][j]);
}
}
a = quick_pow(a, m);
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
printf("%d%c", a.m[i][j], j==n-1 ? '\n' : ' ');
}
}
return 0;
}