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
解题思路:
Sum(k) = a ^ 1 + a ^ 2 + ... + a ^ k
当k是偶数时:Sum(k) = Sum(k / 2) * (a ^ (k / 2) + 1)
当k是奇数时:Sum(k) = Sum(k / 2) * (a ^ (k / 2) + 1) + a ^ k
通过递归求出Sum(k)
注意:运算的时候注意取模的地方,否则很容易在还未取模的时候就已经超int范围,递归的时候先用中间量存Sum(k / 2),否则会超时。
AC代码:
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 35;
int n, k, m;
class ju
{
public:
int c[maxn][maxn];
ju()
{
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
{
c[i][j] = 0;
if(i == j)
c[i][j] = 1;
}
}
friend ju operator *(ju j1,ju j2)
{
ju j3;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
j3.c[i][j] = 0;
for(int h = 0; h < n; h++)
{
j3.c[i][j] += j1.c[i][h] * j2.c[h][j];
j3.c[i][j] %= m;
}
}
}
return j3;
}
friend ju operator +(ju j1, ju j2)
{
ju j3;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
j3.c[i][j] = j2.c[i][j] + j1.c[i][j];
j3.c[i][j] %= m;
}
}
return j3;
}
};
ju a, ans;
ju pow(ju x, int k)
{
ju res;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
{
res.c[i][j] = 0;
if(i == j)
res.c[i][j] = 1;
}
while(k)
{
if(k & 1)
res = res * x;
k >>= 1;
x = x * x;
}
return res;
}
ju Sum(ju x,int k)
{
if(k == 1)
return x;
else
{
ju temp = Sum(x, k >> 1);
if(k % 2)
return temp * pow(x, k >> 1) + temp + pow(x, k);
else
return temp * pow(x, k >> 1) + temp;
}
}
int main()
{
scanf("%d%d%d", &n, &k, &m);
for(int i = 0; i < n; i++)
for(int j = 0; j< n; j++)
{
scanf("%d", &a.c[i][j]);
//a.c[i][j] %= m;
}
ans = Sum(a, k);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(j == n - 1)
printf("%d\n", ans.c[i][j]);
else
printf("%d ", ans.c[i][j]);
}
}
return 0;
}