题目链接:https://vjudge.net/problem/UVA-10870
题意:给出一个线性递推,求f(n) mod m
解题方案:线性递推,可以用矩阵相乘描述,矩阵快速幂。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
#define FOR(i,k,n) for(int i=k;i<n;i++)
#define FORR(i,k,n) for(int i=k;i<=n;i++)
#define scan(a) scanf("%d",&a)
#define scann(a,b) scanf("%d%d",&a,&b)
#define scannn(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define mst(a,n) memset(a,n,sizeof(a))
#define ll long long
#define N 20
#define mod 1000000007
#define INF 0x3f3f3f3f
const double eps=1e-8;
const double pi=acos(-1.0);
int d, n, m;
ll S[N];
typedef struct Mat{
ll mat[N][N];
}Mat;
Mat A,res;
Mat operator * (Mat a, Mat b)
{
Mat c;
mst(c.mat, 0);
for(int i = 0; i < d; i++){
for(int k = 0; k < d; k++){
if(a.mat[i][k]==0) continue;
for(int j = 0; j < d; j++){
c.mat[i][j] = (c.mat[i][j] + a.mat[i][k] * b.mat[k][j] % m) % m;
}
}
}
return c;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(~scanf("%d%d%d",&d, &n, &m)){
if(!d && !n && !m) break;
mst(A.mat, 0);
FOR(i, 0, d-1){
A.mat[i][i+1] = 1;
}
for(int i = d-1; i >= 0; i --){
scanf("%lld", &A.mat[d-1][i]);
}
FOR(i, 0, d){
scanf("%lld", &S[i]);
}
mst(res.mat, 0);
FOR(i, 0, d) res.mat[i][i] = 1;
if(n <= d){
printf("%lld\n",S[n-1]);
continue;
}
n -= d;
while(n){
if(n & 1) res = res * A;
n >>= 1;
A = A * A;
}
ll ans = 0;
FOR(i, 0, d){
ans = (ans + res.mat[d-1][i] * S[i] % m) % m;
}
printf("%lld\n", ans);
}
return 0;
}