UVA 11149 Power of Matrix

时间:2025-01-15 00:03:56

矩阵快速幂。

UVA 11149 Power of Matrix

读入A矩阵之后,马上对A矩阵每一个元素%10,否则会WA.....

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std; int MOD=;
int n,m; struct Matrix
{
int A[][];
int R, C;
Matrix operator*(Matrix b);
}; Matrix A, X, Y, Z; int mod(int a, int b)
{
if (a >= ) return a%b;
if (abs(a) % b == ) return ;
return (a + b*(abs(a) / b + ));
} Matrix Matrix::operator*(Matrix b)
{
Matrix c;
memset(c.A, , sizeof(c.A));
int i, j, k;
for (i = ; i <= R; i++)
for (j = ; j <= C; j++)
for (k = ; k <= C; k++)
c.A[i][j] = mod((c.A[i][j] + mod(A[i][k] * b.A[k][j], MOD)), MOD);
c.R=R; c.C=b.C;
return c;
} void read()
{
A.R=A.C=n;
for(int i=;i<=n;i++)
for(int j=;j<=n;j++) {
scanf("%d",&A.A[i][j]);
A.A[i][j]=A.A[i][j]%MOD;
}
} void init()
{
m=m-;
memset(Y.A,,sizeof Y.A);
memset(Z.A,,sizeof Z.A);
memset(X.A,,sizeof X.A); Y.R=*n; Y.C=*n;
for(int i=;i<=*n;i++) Y.A[i][i]=; Z.R=n; Z.C=*n;
for(int i=;i<=n;i++) Z.A[i][i]=;
for(int i=;i<=n;i++) for(int j=n+;j<=*n;j++) Z.A[i][j]=A.A[i][j-n]; X.R=*n; X.C=*n;
for(int i=;i<=n;i++) X.A[i][i]=;
for(int i=;i<=n;i++) for(int j=n+;j<=*n;j++) X.A[i][j]=A.A[i][j-n];
for(int i=n+;i<=*n;i++) for(int j=n+;j<=*n;j++) X.A[i][j]=A.A[i-n][j-n];
} void work()
{
while (m)
{
if (m % == ) Y = Y*X;
m = m >> ;
X = X*X;
}
Z = Z*Y; for(int i=;i<=n;i++)
{
for(int j=n+;j<=*n;j++)
{
printf("%d",Z.A[i][j]%MOD);
if(j<*n) printf(" ");
else printf("\n");
}
}
printf("\n");
} int main()
{
while(~scanf("%d%d",&n,&m))
{
if(!n) continue;
read();
init();
work();
}
return ;
}