Topic Links:
http://poj.org/problem?id=3233
Main topic:
Given a n*n matrix A and an integer k, it is required to calculate s = a + a^2 + a^3 + ... + a^k.
Ideas:
The a^i of each item is calculated by using the Matrix fast power, and then the matrix is added, taking into account that the K value is very large, all using
Two-part solution.
AC Code:
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring>using namespace std;const int MAXN = 110;struct matrax{int M[MAXN][MAXN];} A,per;int n,m;void Init () {for (int i = 0, i < n; ++i) for (int j = 0; J < N; ++j) {scanf ("%d", &a.m[i][j]); A.M[I][J]%= m; PER.M[I][J] = (i = = j); }}matrax Add (Matrax A,matrax b) {Matrax C; for (int i = 0, i < n; ++i) {for (int j = 0; j < N; ++j) {C.m[i][j] = (A.m[i][j] + b.m[ I][J])% M; }} return C;} Matrax Multi (Matrax A,matrax b) {Matrax C; for (int i = 0, i < n; ++i) {for (int j = 0; j < N; ++j) {c.m[i][j] = 0; for (int k = 0; k < N; ++k) {C.m[i][j] + = a.m[i][k] * B.m[k][j]; } C.m[i][j]%= m; }} return C;} Matrax Power (int k) {Matrax P,ans = per; p = A; while (k) { if (k&1) {ans = Multi (ans,p); k--; } else {k >>= 1; p = Multi (p,p); }} return ans; Matrax matraxsum (int k) {if (k = = 1) return A; Matrax temp,b; temp = Matraxsum (K/2); if (k&1) {b = Power (k/2+1); temp = ADD (Temp,multi (temp,b)); temp = ADD (temp,b); } else {b = Power (K/2); temp = ADD (Temp,multi (temp,b)); } return temp;} int main () {int k; while (~SCANF ("%d%d%d", &n,&k,&m)) {Init (); Matrax ans = matraxsum (k); for (int i = 0, i < N; ++i) {for (int j = 0; j < N-1; ++j) {printf ("%d" , Ans.m[i][j]); } printf ("%d\n", ans.m[i][n-1]); }} return 0;}
POJ3233 matrix Power Series "matrices fast Power"