描述
Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.
输入
The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 109) and m (m < 104). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.
输出
Output the elements of S modulo m in the same way as A is given.
样例输入
2 2 4
0 1
1 1
样例输出
1 2
2 3
题解:一个是矩阵快速幂,还有就是像(k^1+k^2+...+k^n-1+k^n)=(k^1+k^2...+k^n/2-1+k^n/2)+(k^n/2+1+k^n/2+2+...+k^n-1+k^n)=(k^1+k^2...+k^n/2-1+k^n/2)+(k^1+k^2...+k^n/2-1+k^n/2)*k^n/2一样来处理。
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<iomanip>
#include<string.h>
#include<set>
#include<string>
#include<map>
#include<bitset>
#pragma warning(disable : 4996)
using namespace std;
//定义矩阵
class Martix
{
public:
long long a[35][35];
Martix()
{
memset(a, 0, sizeof(a));
}
private:
};
//a是初始输入矩阵,ans是输出的答案
Martix a, ans;
long long n, m;
//矩阵的乘
Martix mul(Martix x, Martix y) {
Martix c;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
for (int k = 1; k <= n; k++)
c.a[i][j] = (c.a[i][j] + x.a[i][k] * y.a[k][j]) % m;
}
}
return c;
}
//矩阵的加
Martix add(Martix x, Martix y)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
x.a[i][j] = (x.a[i][j] + y.a[i][j]) % m;
}
}
return x;
}
//矩阵快速幂
Martix ksm(Martix x, int k) {
Martix res;
for (int i = 1; i <= n; i++)
res.a[i][i] = 1;
while (k) {
if (k & 1) res = mul(res, x);
x = mul(x, x);
k >>= 1;
}
return res;
}
//求解(a^1+a^2+...+a^k-1+a^k)的值
Martix solve(int k)
{
if (k == 1) return a;
//求解(a^1+a^2+...+a^k/2-1+a^k/2)的值
Martix t = solve(k >> 1);
//如果k是偶数求出(a^1+a^2+...+a^k/2-1+a^k/2)后自己加上自己乘(a^k/2)的值就行了
//如果k是奇数上面的方法其实只求了(a^1+a^2+...+a^k-1+a^k-1),因为是奇数qwq,记得加上a^k
if (k & 1)
return add(ksm(a, k), add(t, mul(t, ksm(a, k >> 1))));
else
return add(t, mul(t, ksm(a, k >> 1)));
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long k;
//输入初始数据
cin >> n >> k >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> a.a[i][j];
}
}
//求解矩阵
ans = solve(k);
//输出
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cout << ans.a[i][j];
if (j == n)
cout << endl;
else
cout << " ";
}
}
return 0;
}