Test instructions
Ask for a recursive (not good how to summarize: ) Value of the function.
i.e. f (n) =a1f (n-1) +a2f (n-2) +...+ADF (n-d);
SOL:
Based on the definition of matrix multiplication we can easily construct a matrix, each time the multiplication can be obtained the next f (n) value and save F (n)-----f (n-d+1) from the epicenter.
A guy like me who's seen the wrong number of algorithms.
The first moment is almost exactly the same as the old man's template-----Just think his writing is more elegant = = (although I feel so many memcpy will not make the constant very big ...) )
CODE:
/*==========================================================================# last modified:2016-03-03 21:11# filename:uva10870.cpp# Description: ==========================================================================*/ #define ME Acrossthesky #include <cstdio> #include <cmath> #include <ctime> #include <string> #in Clude <cstring> #include <cstdlib> #include <iostream> #include <algorithm> #include <set> ; #include <map> #include <stack> #include <queue> #include <vector> #define LOWBIT (x) (x) & (-X ) #define for (I,A,B) for ((i) = (a);(i) <= (b);(i) + +) #define FORP (I,A,B) for (int i= (a); i<= (b); i++) #define FORM (i,a,b ) for (int i= (a); i>= (b); i--) #define LS (A, a) (((a) + (b)) << 1) #define RS (A, B) (((a) + (c)) >> 1) #define GETLC (a) ch[(a)][0] #define GETRC (a) ch[(a)][1] #define MAXN 100#define MAXM 100000 #define PI 3.1415926535898 #define _E 2.71 8281828459 #define INF 1070000000 using Namespace std; typedef long Long LL; typedef unsigned long long ull; Template<class t> inline void read (t& num) {bool start=false,neg=false; char c; num=0; while ((C=getchar ())!=eof) {if (c== '-') start=neg=true; else if (c>= ' 0 ' && c<= ' 9 ') {start=true; num=num*10+c-' 0 '; } else if (start) break; } if (neg) num=-num; }/*==================split line==================*/typedef long Long Matrix[maxn][maxn];typedef long VECTOR[MAXN ];int n,m,d,sz;void Matrix_mul (Matrix A,matrix B,matrix res) {matrix C;memset (c,0,sizeof (C)); Forp (i,0,sz-1) Forp (j,0,sz-1) Forp (k,0,sz-1) c[i][j]= (C[i][j]+a[i][k]*b[k][j])%m;memcpy (res,C,sizeof (C));} void Matrix_pow (Matrix A,int N,matrix res) {matrix a,r;memcpy (a,a,sizeof (A)); memset (r,0,sizeof (R)); Forp (i,0,sz-1) r[i][i]=1;while (n) {if (n&1) Matrix_mul (r,a,r); n >>= 1;matrix_mul (a,a,a);} memcpy (res,r,sizeof (R));} void transform (vector d,matrix a,vector res) {vector R;memset (R,0,sizeof (R)); Forp (i,0,sz-1) Forp (j,0,sz-1) r[j]= (R[j]+d[i]*a[i][j])%m;memcpy (res,r,sizeof (R));} int main () {while (scanf ("%d%d%d", &d,&n,&m)!=eof) {if (d==0 && n==0 && m==0) return 0; Matrix A; Vector a,f; Forp (i,0,d-1) {read (a[i]); a[i]%=m;} FORM (i,d-1,0) {read (f[i]); f[i]%=m;} memset (a,0,sizeof (A)); Forp (i,0,d-1) a[i][0]=a[i]; Forp (i,1,d-1) A[i-1][i]=1;sz=d;matrix_pow (a,n-d,a); transform (f,a,f); cout << f[0] << Endl;} }
UVa 10870 & Matrix Fast Power