Matrix Power Series


#include <iostream>
#include <cstdio>

using namespace std;

struct M
{
   int n;
   int m[30][30];
   M(){
	   for(int i=0;i<30;i++)
		   for(int j=0;j<30;j++)
			   m[i][j]=0;
   }
};
int mod;
M orginal;

M mul(M a,M b)
{
	M c;c.n=orginal.n;
	for(int i=0;i<a.n;i++)
		for(int j=0;j<a.n;j++)
			for(int k=0;k<a.n;k++)
				c.m[i][j]=(c.m[i][j]+a.m[i][k]*b.m[k][j])%mod;
	return c;
}

M quick(int k)
{
	if(k==1)return orginal;
	if(k%2)
	{
		M c=quick(k/2);c.n=orginal.n;
		return mul(mul(c,c),orginal);
	}
	else 
	{
		M c= quick(k/2);c.n=orginal.n;
		return mul(c,c);
	}
	return orginal;
}

M add(M a,M b)
{
	M c;c.n=a.n;
	for(int i=0;i<a.n;i++)
		for(int j=0;j<a.n;j++)
			c.m[i][j] = (a.m[i][j]+b.m[i][j])%mod;
	return c;
}

M longquick(int k)
{
	if(k==1) return orginal;
	if(k==2) return add(orginal,mul(orginal,orginal));
	if(k%2)
	{
		M temp = longquick(k/2);temp.n=orginal.n;
		M en = quick(k/2+1);en.n=orginal.n;
		return add(temp,add(en,mul(en,temp)));
	}
	else
	{
		M temp = longquick(k/2);temp.n=orginal.n;
		return add(temp,mul(temp,quick(k/2)));
	}
	return orginal;
}

void print(M a)
{
	for(int i=0;i<a.n;i++)
	{
		for(int j=0;j<a.n;j++)
		{
		    if(j==0) {cout<<a.m[i][j];continue;}
			else cout<<" "<<a.m[i][j];
		}
		cout<<endl;
	}
}
void init()
{
	int n,k;
	while(cin>>n>>k>>mod)
	{
		orginal.n=n;
		for(int i=0;i<n;i++)
			for(int j=0;j<n;j++)
			{
				cin>>orginal.m[i][j];
			}
	M c=longquick(k);
	print(c);
	}


}

int main()
{
	init();
	return 0;
}


你可能感兴趣的:(c,ini,include,Matrix)