题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4965
4 2 5 5 4 4 5 4 0 0 4 2 5 5 1 3 1 5 6 3 1 2 3 0 3 0 2 3 4 4 3 2 2 5 5 0 5 0 3 4 5 1 1 0 5 3 2 3 3 2 3 1 5 4 5 2 0 0
14 56
思路:
(这里把题目中的k叙述为m)
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int MAXN = 1017; #define mod 6 struct Matrix { int mat[6][6]; }; int n, m;//矩阵大小 int A[MAXN][6],B[6][MAXN],C[MAXN][6],D[MAXN][MAXN]; Matrix T, E; Matrix mul(Matrix a,Matrix b) { Matrix t; memset(t.mat,0,sizeof(t.mat)); for(int i = 0; i < m; i++)//最矩阵大小是m*m的 { for(int j = 0; j < m; j++) { for(int k = 0; k < m; k++) { t.mat[i][j]+=a.mat[i][k]*b.mat[k][j]; t.mat[i][j]%=mod; } } } return t; } Matrix quickP(int k) { Matrix p = T, mm; memset(mm.mat,0,sizeof(mm.mat)); for(int i = 0; i < m; i++)//单位矩阵 { mm.mat[i][i]=1; } while(k) { if(k & 1) mm = mul(mm,p); p = mul(p,p); k >>= 1 ; } return mm; } void init() { memset(T.mat,0,sizeof(T.mat)); memset(C,0,sizeof(C)); memset(D,0,sizeof(D)); } int main() { while(~scanf("%d%d",&n,&m)) { if(n == 0 && m == 0) break; init(); for(int i = 0; i < n; i++)//矩阵A的大小n*m { for(int j = 0; j < m; j++) { scanf("%d",&A[i][j]); } } for(int i = 0; i < m; i++)//矩阵B的大小m*n { for(int j = 0; j < n; j++) { scanf("%d",&B[i][j]); } } for(int i = 0; i < m; i++)//矩阵T = B*A大小为m*m { for(int j = 0; j < m; j++) { for(int k = 0; k < n; k++) { T.mat[i][j] += B[i][k]*A[k][j]; T.mat[i][j] %= mod; } } } E = quickP(n*n-1);//只需要乘n*n-1次 for(int i = 0; i < n; i++)//矩阵C = A*E 大小为n*m { for(int j = 0; j < m; j++) { for(int k = 0; k < m; k++) { C[i][j] += A[i][k]*E.mat[k][j]; C[i][j] %= mod; } } } int ans = 0; for(int i = 0; i < n; i++)//矩阵D = C*B大小为n*n { for(int j = 0; j < n; j++) { for(int k = 0; k < m; k++) { D[i][j] += C[i][k]*B[k][j]; } ans += D[i][j]%mod; } } printf("%d\n",ans); } return 0; }
hdu 4965 Fast Matrix Calculation(矩阵快速幂),布布扣,bubuko.com
hdu 4965 Fast Matrix Calculation(矩阵快速幂)
原文地址:http://blog.csdn.net/u012860063/article/details/38707419