首页 > 代码库 > POJ3233 Matrix Power Series

POJ3233 Matrix Power Series

poj3233 题意:给定矩阵A和整数k 求矩阵S=A+A^2+.....+A^k

如果把矩阵A换成整数a 我们可以拿矩阵快速幂得到答案

而矩阵中的每一个元素 如果换成一个矩阵 所有的性质也是成立的 这叫分块矩阵 所以 乱搞一下就好了

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
typedef long long int LL;
const LL mt_MAXN=60;const LL mt_MAXM=60;
struct Matrix
       {
        LL n,m;
		LL MOD;
		LL a[mt_MAXN][mt_MAXM];
		void clear()
				{
				 n=m=0;
				 memset(a,0,sizeof(a));
				}
		Matrix operator +(const Matrix &b)const
            {
			Matrix tmp;
			tmp.n=n;tmp.m=m;tmp.MOD=MOD;
            for(LL i=0;i<n;++i)
				for(LL j=0;j<m;++j)
					tmp.a[i][j]=(a[i][j]+b.a[i][j])%MOD;
 			 return tmp;
         	}
        Matrix operator -(const Matrix &b)const
            {
			Matrix tmp;
			tmp.n=n;tmp.m=m;tmp.MOD=MOD;
            for(LL i=0;i<n;++i)
				for(int j=0;j<m;++j)
					tmp.a[i][j]=(a[i][j]-b.a[i][j]+MOD)%MOD;
 			 return tmp;
         	}
		Matrix operator *(const Matrix &b)const
			{
			 Matrix tmp;
			 tmp.clear();
			 tmp.n=n;tmp.m=b.m;tmp.MOD=MOD;
 			 for(LL i=0;i<n;++i)
				for(LL j=0;j<b.m;++j)
					for(LL k=0;k<m;++k)
						tmp.a[i][j]=(tmp.a[i][j]+((a[i][k])*(b.a[k][j]))%MOD+MOD)%MOD;
			 return tmp;
			}
				
		Matrix iden()
				{
				 Matrix x;
				 memset(x.a,0,sizeof(x.a));
				 x.m=n;x.n=n;
				 x.MOD=MOD;
				 for(LL i=0;i<n;++i)
				     x.a[i][i]=1;
				 return x;
				}
		Matrix pow(LL t) 
				{
				 Matrix now;
				 now.n=n;now.m=m;now.MOD=MOD;
				 memset(now.a,0,sizeof(now.a));
				 for(LL i=0;i<n;++i)
					for(LL j=0;j<m;++j)
						now.a[i][j]=a[i][j];
				 for(LL i=1;i<t;i++)
					now=now*now;
				 return now;
				}
		Matrix qpow(LL t)
				{
				 if(n==0)return iden();
				 Matrix now;
				 now.clear();
				 now.n=n;now.m=m;now.MOD=MOD;
				 now=pow(1);
				 Matrix ans;
				 	 ans.clear();
				 ans.n=n;ans.m=m;ans.MOD=MOD;
			     ans=ans.iden();
				 while(true)
					{
					 if(t%2==1)ans=ans*now;
					 t=t/2;
					 now=now*now;
					 if(t==0)break;
					}
				 return ans;
				}
	   };
int main()
{
 ios::sync_with_stdio(false);
 freopen("t.txt","r",stdin);
 int n,k,m;
 cin>>n>>k>>m;
 Matrix A;
 A.n=n*2;
 A.m=n;
 Matrix B;
 B.n=B.m=n*2;
 A.MOD=B.MOD=m;
 for(int i=0;i<n;i++)
 	B.a[i][i]=B.a[i][i+n]=1;
 for(int i=0;i<n;i++)
 	for(int j=0;j<n;j++)
 		{
		 cin>>A.a[i+n][j];
		 B.a[i+n][j+n]=A.a[i+n][j];
		}
 B=B.qpow(k);
 Matrix ans=B*A;
 for(int i=0;i<n;i++)
 	{
 		for(int j=0;j<n-1;j++)
 			cout<<ans.a[i][j]%m<<" ";
 	    cout<<ans.a[i][n-1]%m<<endl;
	}
 return 0;
}

  快速幂写的常数太大也会TLE

POJ3233 Matrix Power Series