矩阵快速幂

题目链接

根据题意找出递推式子,利用矩阵快速幂求得即可,代码如下:

#include<bits/stdc++.h>
using namespace std;
using ll =long long;
const int M=1e9+7;
ll T;
struct m{
  ll c[2][2];
  m(){memset(c,0,sizeof c);}
};
m operator*(m &x,m &y){
  m t;
  for(int i=0;i<2;i++)
    for(int j=0;j<2;j++)
      for(int k=0;k<2;k++)
        t.c[i][j]=(t.c[i][j]+x.c[i][k]*y.c[k][j])%M;
  return t;
}
void solved()
{
    ll n,k; cin>>n>>k;
    ll f1=k;
    ll f2=((k*k-2)%M+M)%M;
    if(n==1) cout<<f1<<'\n';
    else if(n==2) cout<<f2<<'\n';
    else{
    m x; x.c[0][0]=k; x.c[0][1]=-1; x.c[1][0]=1; x.c[1][1]=0;
    m res;
    for(int i=0;i<2;i++) res.c[i][i]=1;
    ll su =n-2;
    while(su)
    {
      if(su&1) res=res*x;
      x=x*x;
      su>>=1;
    }
    cout<<((res.c[0][0]*f2+res.c[0][1]*f1)%M+M)%M<<'\n';
    }
}
int main()
{
  cin>>T;
  while(T--)
  {
    solved();
  }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值