UVA10870 Recurrences —— 矩阵快速幂

来源:互联网 发布:最低价网淘宝 编辑:程序博客网 时间:2024/05/16 09:24

题目链接:https://vjudge.net/problem/UVA-10870



题意:

典型的矩阵快速幂的运用。比一般的斐波那契数推导式多了几项而已。


更难一点的:http://blog.csdn.net/dolfamingo/article/details/76037826



代码如下:

#include <bits/stdc++.h>#define rep(i,s,t) for(int (i)=(s); (i)<=(t); (i)++)#define ms(a,b) memset((a),(b),sizeof((a)))using namespace std;typedef long long LL;const int INF = 2e9;const LL LNF = 9e18;const double eps = 1e-6;const int mod = 10000007;const int maxn = 2e5+10;struct MA{    LL mat[20][20];    void init()    {        rep(i,1,19) rep(j,1,19)            mat[i][j] = (i==j);    }};LL n,d,m;LL a[20],f[20];MA mul(MA x, MA y){    MA tmp;    ms(tmp.mat,0);    rep(i,1,d) rep(j,1,d) rep(k,1,d)        tmp.mat[i][j] += (1LL*x.mat[i][k]*y.mat[k][j])%m, tmp.mat[i][j] %= m;    return tmp;}MA qpow(MA x, LL y){    MA s;    s.init();    while(y)    {        if(y&1) s = mul(s,x);        x = mul(x,x);        y >>= 1;    }    return s;}int main(){    while(scanf("%lld%lld%lld",&d,&n,&m) && (d || n||m))    {        rep(i,1,d)            scanf("%lld",&a[i]);        rep(i,1,d)            scanf("%lld",&f[i]);        MA x;        ms(x.mat,0);        rep(i,1,d)            x.mat[1][i] = a[i];        rep(i,2,d)            x.mat[i][i-1] = 1;        x = qpow(x,n-d);        LL ans = 0;        rep(i,1,d)            ans += (1LL*x.mat[1][i]*f[d-i+1])%m, ans %= m;        printf("%lld\n",ans);    }}


原创粉丝点击