【矩阵快速幂】nyoj301 递推求值

递推求值

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 4
描述

给你一个递推公式:

f(x)=a*f(x-2)+b*f(x-1)+c

并给你f(1),f(2)的值,请求出f(n)的值,由于f(n)的值可能过大,求出f(n)对1000007取模后的值。

注意:-1对3取模后等于2

输入
第一行是一个整数T,表示测试数据的组数(T<=10000)
随后每行有六个整数,分别表示f(1),f(2),a,b,c,n的值。
其中0<=f(1),f(2)<100,-100<=a,b,c<=100,1<=n<=100000000 (10^9)
输出
输出f(n)对1000007取模后的值
样例输入
2
1 1 1 1 0 5
1 1 -1 -10 -100 3
样例输出
5
999896


 构造两个3*3的矩阵     f2  0    0       b    a   c

                                     f1   0   0  和  1   0   0

                                      1   0   0        0   0   1

code:

//矩阵快速幂
#include<stdio.h>
#include<iostream>
#include<string.h>
#define mod 1000007
#define N 5
typedef long long LL;
using namespace std;
struct Matrix
{
    LL mat[N][N];
};
Matrix unit_matrix =
{
    1,0,0,
    0,1,0,
    0,0,1
};//单位矩阵
Matrix mul(Matrix a,Matrix b)//矩阵相乘
{
    Matrix res;
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
        {
            res.mat[i][j]=0;
            for(int k=0; k<3; k++)
                res.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
            res.mat[i][j]%=mod;
        }
        return res;
}
Matrix pow_matrix(Matrix a,LL n)//矩阵快速幂
{
    Matrix res=unit_matrix;
    while(n)
    {
        if(n&1)
        {
            res=mul(res,a);
        }
        a=mul(a,a);
        n>>=1;
    }
    return res;
}
int main()
{
   int T;
   scanf("%d",&T);
   while(T--)
   {
       LL a,b,c,f1,f2,n;
       cin>>f1>>f2>>a>>b>>c>>n;
       Matrix A,B,ans;
       memset(A.mat,0,sizeof(A.mat));
       memset(B.mat,0,sizeof(B.mat));
       A.mat[0][0]=f2,A.mat[1][0]=f1,A.mat[2][0]=1;
       B.mat[0][0]=b,B.mat[0][1]=a,B.mat[0][2]=c;
       B.mat[1][0]=1,B.mat[2][2]=1;
       if(n==1)
      cout<<f1<<endl;
      else if(n==2)
        cout<<f2<<endl;
      else
      {
          ans=pow_matrix(B,n-2);
          ans=mul(ans,A);
          ans.mat[0][0]=(ans.mat[0][0]+mod)%mod;
          cout<<ans.mat[0][0]<<endl;
      }

   }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值