POJ 3233 Matrix Power Series (Matrix optimization)
Ask S [k] = A + A ^ 2 +... + A ^ k
Using the rapid power of A matrix, we can quickly obtain the k power of A matrix, but this question is A sum. If we still follow the original method, we will calculate k times, which is unacceptable in complexity.
We can construct A matrix (A 0)
(E)
Now let S [k] = E + A ^ 2 +... + A ^ (k-1)
So (A ^ k) (A 0) (A ^ (k-1) (A 0) ^ k (E)
=
(S [k]) (E) (S [k-1]) (E) (0)
Then, we only need to calculate S [k + 1] = E + A +... + A ^ k
Then, just move the diagonal line element-1.
For details, see the code:
#include
#include
#include#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define Max(a,b) ((a)>(b)?(a):(b))#define Min(a,b) ((a)<(b)?(a):(b))using namespace std;typedef long long ll;const double PI = acos(-1.0);const double eps = 1e-6;const int INF = 1000000000;const int mod = 10007;const int maxn = 100;int T,n,m,k;typedef vector
vec;typedef vector
mat;mat mul(mat &a, mat &b) { mat c(a.size(), vec(a[0].size())); for(int i = 0; i < a.size(); i++) { for(int k = 0; k < b.size(); k++) { for(int j = 0; j < b[0].size(); j++) { c[i][j] = (c[i][j] + a[i][k]*b[k][j]) % m; } } } return c;}mat pow(mat a, ll n) { mat b(a.size(), vec(a[0].size())); for(int i = 0; i < a.size(); i++) { b[i][i] = 1; } while(n > 0) { if(n & 1) b = mul(b, a); a = mul(a, a); n >>= 1; } return b;}int main() { scanf("%d%d%d",&n,&k,&m); mat a(2*n, vec(2*n)); for(int i=0;i