标签:
矩阵快速幂。
读入A矩阵之后,马上对A矩阵每一个元素%10,否则会WA.....
#include<cstdio> #include<cstring> #include<cmath> #include<vector> #include<algorithm> using namespace std; int MOD=10; int n,m; struct Matrix { int A[90][90]; int R, C; Matrix operator*(Matrix b); }; Matrix A, X, Y, Z; int mod(int a, int b) { if (a >= 0) return a%b; if (abs(a) % b == 0) return 0; return (a + b*(abs(a) / b + 1)); } Matrix Matrix::operator*(Matrix b) { Matrix c; memset(c.A, 0, sizeof(c.A)); int i, j, k; for (i = 1; i <= R; i++) for (j = 1; j <= C; j++) for (k = 1; 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=1;i<=n;i++) for(int j=1;j<=n;j++) { scanf("%d",&A.A[i][j]); A.A[i][j]=A.A[i][j]%MOD; } } void init() { m=m-1; memset(Y.A,0,sizeof Y.A); memset(Z.A,0,sizeof Z.A); memset(X.A,0,sizeof X.A); Y.R=2*n; Y.C=2*n; for(int i=1;i<=2*n;i++) Y.A[i][i]=1; Z.R=n; Z.C=2*n; for(int i=1;i<=n;i++) Z.A[i][i]=1; for(int i=1;i<=n;i++) for(int j=n+1;j<=2*n;j++) Z.A[i][j]=A.A[i][j-n]; X.R=2*n; X.C=2*n; for(int i=1;i<=n;i++) X.A[i][i]=1; for(int i=1;i<=n;i++) for(int j=n+1;j<=2*n;j++) X.A[i][j]=A.A[i][j-n]; for(int i=n+1;i<=2*n;i++) for(int j=n+1;j<=2*n;j++) X.A[i][j]=A.A[i-n][j-n]; } void work() { while (m) { if (m % 2 == 1) Y = Y*X; m = m >> 1; X = X*X; } Z = Z*Y; for(int i=1;i<=n;i++) { for(int j=n+1;j<=2*n;j++) { printf("%d",Z.A[i][j]%MOD); if(j<2*n) printf(" "); else printf("\n"); } } printf("\n"); } int main() { while(~scanf("%d%d",&n,&m)) { if(!n) continue; read(); init(); work(); } return 0; }
标签:
原文地址:http://www.cnblogs.com/zufezzt/p/5229575.html