传送门
矩阵快速幂模板题,构造的矩阵为
#include
#include
#include
using namespace std;
#define LL long long
const LL mod=1e9+7;
struct hp{
LL a[5][5];
}con;
LL n;
LL ans[5][5],fib[5][5];
inline hp work(hp a,hp b){
hp c;
memset(c.a,0,sizeof(c.a));
for (int i=1;i<=2;++i)
for (int j=1;j<=2;++j)
for (int k=1;k<=2;++k)
c.a[i][j]=(c.a[i][j]+a.a[i][k]*b.a[k][j]%mod)%mod;
return c;
}
inline hp fast_pow(hp a,LL p){
hp ans=con;
for (;p;p>>=1,a=work(a,a))
if (p&1)
ans=work(ans,a);
return ans;
}
int main(){
while (~scanf("%lld",&n)){
if (n==1||n==2){
printf("1\n");
continue;
}
con.a[1][1]=con.a[1][2]=con.a[2][1]=1; con.a[2][2]=0;
if (n>3) con=fast_pow(con,n-3);
fib[1][1]=fib[2][1]=1;
memset(ans,0,sizeof(ans));
for (int i=1;i<=2;++i)
for (int j=1;j<=1;++j)
for (int k=1;k<=2;++k)
ans[i][j]=(ans[i][j]+con.a[i][k]*fib[k][j]%mod)%mod;
printf("%lld\n",ans[1][1]);
}
}