POJ 3233 Matrix Power Series 矩阵等比数列求和
和前面有一题是一样的做法吧。
A^1+A^2+A^3+A^4 = A^1+A^2+A^2*(A^1+A^2)类似这样搞就可以二分处理了。
#include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <stack> #include <map> #include <set> #include <climits> #include <iostream> #include <string> using namespace std; #define MP make_pair #define PB push_back typedef long long LL; typedef unsigned long long ULL; typedef vector<int> VI; typedef pair<int, int> PII; typedef pair<double, double> PDD; const int INF = INT_MAX / 3; const double eps = 1e-8; const LL LINF = 1e17; const double DINF = 1e60; const int maxn = 40; LL N, K, MOD; struct Matrix { int n, m; LL data[maxn][maxn]; Matrix(int n = 0, int m = 0): n(n), m(m) { memset(data, 0, sizeof(data)); } }; Matrix operator * (Matrix a, Matrix b) { Matrix ret(a.n, b.m); for(int i = 1; i <= a.n; i++) { for(int j = 1; j <= b.m; j++) { for(int k = 1; k <= a.m; k++) { ret.data[i][j] += a.data[i][k] * b.data[k][j]; ret.data[i][j] %= MOD; } } } return ret; } Matrix operator + (Matrix a, Matrix b) { for(int i = 1; i <= a.n; i++) { for(int j = 1; j <= a.m; j++) { a.data[i][j] += b.data[i][j]; a.data[i][j] %= MOD; } } return a; } Matrix pow(Matrix mat, LL p) { if(p == 1) return mat; Matrix ret = pow(mat * mat, p / 2); if(p & 1) ret = ret * mat; return ret; } Matrix calc(Matrix mat, LL K) { if(K == 1) return mat; Matrix ret = calc(mat, K / 2); ret = ret + pow(mat, K / 2) * ret; if(K & 1) ret = ret + pow(mat, K); return ret; } int main() { while(scanf("%lld%lld%lld", &N, &K, &MOD) != EOF) { Matrix mat(N, N); for(int i = 1; i <= N; i++) { for(int j = 1; j <= N; j++) { scanf("%lld", &mat.data[i][j]); } } mat = calc(mat, K); for(int i = 1; i <= N; i++) { for(int j = 1; j <= N; j++) { printf("%lld ", mat.data[i][j]); } puts(""); } } return 0; }