//矩阵快速幂,本题二阶矩阵
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
const int mod = 1e9+7;
struct Matrix
{
long long mat[2][2];
Matrix()
{
memset(mat,0,sizeof(mat));
}
Matrix operator * (const Matrix &b)
{
Matrix res;
for (int i=0; i<2; ++i)
{
for (int j=0; j<2; ++j)
{
for (int k=0; k<2; ++k)
{
res.mat[i][j]+=mat[i][k]*b.mat[k][j];
res.mat[i][j]%=mod;
}
}
}
return res;
}
};
Matrix operator ^ (Matrix a,long long n)
{
Matrix res;
for (int i=0; i<2; ++i)
res.mat[i][i]=1;
while(n)
{
if(n&1)
res=res*a;
a=a*a;
n>>=1;
}
return res;
}
int main()
{
long long n, m;
Matrix a, s;
//推导的矩阵内容
a.mat[0][0] = 3;
a.mat[0][1] = 1;
a.mat[1][0] = 1;
a.mat[1][1] = 3;
scanf("%I64d", &n);
if(n == 0)
{
puts("1");
return 0;
}
s = a^(n-1);//矩阵快速幂的应用
m = (s.mat[0][0]*3+s.mat[0][1]*1)%mod;//最后的结果式子
printf("%I64d
",m);
}
题目链接