UVA10870 Recurrences —— 矩阵快速幂

题目链接: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);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值