题意:
给出n,求出ans
思路:
既然奇数和偶数的推导公式不一样,
那就把奇数偶数都弄到一个矩阵里,这样就能统一推导了
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<map>
#include<set>
using namespace std;
#define lowbit(x) (x&(-x))
typedef long long LL;
const int maxn = 100005;
const int inf=(1<<28)-1;
#define Matrix_Size 5
LL MOD;
int Size;
struct Matrix
{
LL mat[Matrix_Size][Matrix_Size];
void clear()
{
memset(mat,0,sizeof(mat));
}
void output()
{
for(int i = 0;i < Size;i++)
{
for(int j = 0;j < Size;j++)
printf("%d ",mat[i][j]);
printf("\n");
}
}
Matrix operator *(const Matrix &b)const
{
Matrix ret;
for(int i = 0;i < Size;i++)
for(int j = 0;j < Size;j++)
{
ret.mat[i][j] = 0;
for(int k = 0;k < Size;k++)
{
long long tmp = (long long)mat[i][k]*b.mat[k][j]%MOD;
ret.mat[i][j] = (ret.mat[i][j]+tmp);
if(ret.mat[i][j]>=MOD)
ret.mat[i][j] -= MOD;
}
}
return ret;
}
};
Matrix pow_M(Matrix a,long long n)
{
Matrix ret;
ret.clear();
for(int i = 0;i < Size;i++)
ret.mat[i][i] = 1;
Matrix tmp = a;
while(n)
{
if(n&1)ret = ret*tmp;
tmp = tmp*tmp;
n>>=1;
}
return ret;
}
int main()
{
LL n;
while(~scanf("%lld%lld",&n,&MOD))
{
Matrix A,B;
A.clear(),B.clear();
Size=3;
A.mat[0][0]=1,A.mat[0][1]=0,A.mat[0][2]=1;
B.mat[0][0]=4;B.mat[0][1]=2;
B.mat[2][0]=1;B.mat[2][2]=1;
if(n==0)
{
printf("0\n");
continue;
}
if(n==1)
{
printf("%d\n",n%MOD);continue;
}
B=pow_M(B,n/2);
A=A*B;
//A.output();
if(n&1) printf("%lld\n",A.mat[0][0]);
else printf("%lld\n",A.mat[0][1]);
}
return 0;
}