Matrix Power Series
Time Limit: 3000MS | Memory Limit: 131072K | |
Total Submissions: 16403 | Accepted: 6980 |
Description
Given a n × n matrix A and a positive integerk, find the sumS =A + A2 + A3 + … +Ak.
Input
The input contains exactly one test case. The first line of input contains three positive integersn (n ≤ 30),k (k ≤ 109) andm (m < 104). Then follownlines each containingn nonnegative integers below 32,768, givingA’s elements in row-major order.
Output
Output the elements of S modulo m in the same way asA is given.
Sample Input
2 2 4 0 1 1 1
Sample Output
1 2 2 3
Source
POJ Monthly--2007.06.03, Huang, Jinsong
题目链接: http://poj.org/problem?id=3233
题目大意:就是求 S = A + A 2 + A 3 + … + Ak咯
题目分析:分析可以得到
k为偶数:sum(k) = (1+A^(k/2)) *( A+A^2+……+A^(k/2)) = (1+A^(k/2)) * sum(k/2)
k为奇数:sum(k) = (1+A^((k-1)/2)) * sum(k/2) + A^k
题目链接: http://poj.org/problem?id=3233
题目大意:就是求 S = A + A 2 + A 3 + … + Ak咯
题目分析:分析可以得到
k为偶数:sum(k) = (1+A^(k/2)) *( A+A^2+……+A^(k/2)) = (1+A^(k/2)) * sum(k/2)
k为奇数:sum(k) = (1+A^((k-1)/2)) * sum(k/2) + A^k
A的几次方快速幂可求
但求的是A^1加到A^k,k十分大
这个还是采取二分思想
先算出来A^1+A^2+..A^(k/2)
再总体乘以(I+A^(k/2)),若k为奇数再加上A^k即可
#include <iostream>
#include <string.h>
using namespace std;
int n,k,mod;
struct matrix
{
long long e[31][31];
}a,x,y;
matrix matrix_mul(matrix a1,matrix b)
{
matrix sum;
memset(sum.e,0,sizeof(sum.e));
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
for(int k=0;k<n;++k)//因为写成i<n改了半个小时 mmp
if(a1.e[i][k]&&b.e[k][j])
sum.e[i][j]=(sum.e[i][j]+a1.e[i][k]*b.e[k][j])%mod;
return sum;
}
matrix matrix_pow(int p)
{
memset(y.e,0,sizeof(y.e));
for(int i=0;i<n;++i)
y.e[i][i]=1;
while(p)
{
if(p&1)
y=matrix_mul(y,a);
p>>=1;
a=matrix_mul(a,a);
}
return y;
}
void add()
{
matrix ans,aa,ak;
ans=matrix_pow(1);
for(int i=2;i<=k/2;++i)
{
aa=matrix_pow(i);
for(int j=0;j<n;++j)
for(int t=0;t<n;++t)
ans.e[j][t]=(ans.e[j][t]+aa.e[j][t])%mod;
}
if(k!=1)
{
ak=matrix_mul(ans,y);
for(int j=0;j<n;++j)
for(int t=0;t<n;++t)
ans.e[j][t]=(ans.e[j][t]+ak.e[j][t])%mod;
}
if(k%2)
{
ak=matrix_pow(k);
for(int j=0;j<n;++j)
for(int t=0;t<n;++t)
ans.e[j][t]=(ans.e[j][t]+ak.e[j][t])%mod;
}
for(int j=0;j<n;++j)
{
for(int t=0;t<n;++t)
cout<<ans.e[j][t]<<' ';
cout<<endl;
}
cout<<endl;
}
int main()
{
cin>>n>>k>>mod;
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
cin>>a.e[i][j];
add();
return 0;
}