转载于:http://xuyemin520.is-programmer.com/posts/26387.html
// A^n.cpp : 定义控制台应用程序的入口点。
//
//2分法求矩阵冥次
//Poj 3233
#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;
//如果矩阵过大或者冥过多都会造成栈溢出
const int MAXN = 31;
int Mod;
typedef struct Matrix
{
int s[MAXN][MAXN];
}M;
int n;
//a+b
M Add(M a, M b)
{
M c;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
c.s[i][j] = (a.s[i][j] + b.s[i][j]) % Mod;
}
}
return c;
}
//a*b
M Multiply(M a, M b)
{
M c;
memset(c.s,0,sizeof(c.s));
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
for(int k=1; k<=n; k++)
{
c.s[i][j] = (c.s[i][j] + (a.s[i][k] * b.s[k][j] % Mod))%Mod ;
}
}
}
return c;
}
//a^t
M Pow(M a, int t)
{
M b;
if(t == 0)
{
memset(b.s,0,sizeof(b.s));
for(int i=1; i<=n; i++)
{
b.s[i][i] = 1;
}
return b;
}
else
{
M k = Pow(a,t/2);
if(t&1) //t为奇数
{
return Multiply(Multiply(k,k),a);
}
else
{
return Multiply(k,k);
}
}
}
//A + A^2 + A^3 + ... + A^t
M Sum(M a, int t)
{
M b;
if(t == 1)
{
return a;
}
else
{
M k = Sum(a,t/2);
if(t&1)
{
M p = Pow(a,t/2+1);
return Add (Add(k,p) , Multiply(k,p) );
}
else
{
return Add(k , Multiply(Pow(a,t/2),k));
}
}
}
int main()
{
M a;
int t;
cin>>n>>t>>Mod;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
cin>>a.s[i][j];
a.s[i][j] %= Mod;
}
}
a = Sum(a,t);
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
cout<<a.s[i][j];
if(j != n)
cout<<" ";
}
cout<<endl;
}
return 0;
}