此题要求的是A+A^2+A^3...+A^k,当然逐个求出作和n^3*k复杂度肯定是要超时的。 所以可以构造一个矩阵Sk = I(单位矩阵) + A + A^2 + A^3...+ A^k-1,
Sk = Sk-1 + Ak-1.
所以就可以构造出矩阵快速幂的形式:
每个方格就是一个n*n的矩阵。 要求A+A^2+A^3...+A^k就是要求Sk+1 - I,求出矩阵的k+1次幂后的2n*2n的大矩阵的右上角的小矩阵即使Sk+1,然后减去单位矩阵即是答案。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
ll n, k, mod;
struct node
{
ll s[100][100];
void init(void){ memset(s, 0, sizeof(s)); }
};
void show(node a, int t)
{
for(int i = 0; i < t; i++)
for(int j = 0; j < t; j++)
{
printf("%d ", a.s[i][j]);
if(j == t-1) printf("\n");
}
}
node mul(node a, node b)
{
node t;
t.init();
for(int i = 0; i < 2*n; i++)
for(int j = 0; j < 2*n; j++)
for(int k = 0; k < 2*n; k++)
t.s[i][j] = (t.s[i][j]+a.s[i][k]*b.s[k][j])%mod;
return t;
}
node mt_pow(node p, int m)
{
node q;
q.init();
for(int i = 0; i < 2*n; i++)
q.s[i][i] = 1;
while(m)
{
if(m&1) q = mul(q, p);
p = mul(p, p);
m /= 2;
}
return q;
}
int main(void)
{
while(~scanf("%lld%lld%lld", &n, &k, &mod))
{
node base;
base.init();
for(int i = 0; i < n; i++)
for(int j = 0; j < 2*n; j ++)
if(i == j || i+n == j) base.s[i][j] = 1;
for(int i = n; i < 2*n; i++)
for(int j = n; j < 2*n; j++)
scanf("%d", &base.s[i][j]);
// show(base, 2*n);
node ans = mt_pow(base, k+1);
// show(ans, 2*n);
for(int i = 0; i < n; i++)
{
for(int j = n; j < 2*n; j++)
{
if(j-n) printf(" ");
if(i+n == j) printf("%lld", (ans.s[i][j]-1+mod)%mod);
else printf("%lld", ans.s[i][j]%mod);
}
printf("\n");
}
}
return 0;
}
Time Limit: 3000MS | Memory Limit: 131072K | |
Total Submissions: 21455 | Accepted: 8997 |
Description
Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.
Input
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
Output the elements of S modulo m in the same way as A is given.
Sample Input
2 2 4 0 1 1 1
Sample Output
1 2 2 3
Source