矩阵快速幂模板

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
struct data
{
 int m[32][32];
};data a;
int n,p,k;
void init(data &x,data y)
{
  for (int i=1;i<=n;i++)
   for (int j=1;j<=n;j++)
    x.m[i][j]=y.m[i][j];
} 
data mul(data x,data y)
{
  data temp;
  for (int i=1;i<=n;i++)
   for (int j=1;j<=n;j++)
   	{
   	  temp.m[i][j]=0;
	  for (int k=1;k<=n;k++)
	   temp.m[i][j]=(temp.m[i][j]+(x.m[i][k]*y.m[k][j])%p)%p;	 
   	}
  return temp;
} 
data quickpow(int x)
{
  data sum;
  for (int i=1;i<=n;i++)
     sum.m[i][i]=1;
  data num;
  init(num,a);
  while (x>0)
   {
   	 if (x&1)
   	  sum=mul(sum,num);
   	 x=x>>1;
   	 num=mul(num,num);
   }
  return sum;
}
int main()
{ 
  scanf("%d%d%d",&n,&k,&p);
  for (int i=1;i<=n;i++)
   for (int j=1;j<=n;j++)
    scanf("%d",&a.m[i][j]);
  data ans=quickpow(k);
  for (int i=1;i<=n;i++)
  {
   for (int j=1;j<=n;j++)
    printf("%d ",ans.m[i][j]);
   printf("\n");
  }
}

你可能感兴趣的:(矩阵快速幂模板)