题解:先打出前几个数,然后套下高斯消元的板子,最后就是矩阵快速幂了
附上代码:
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long ll;
struct node{
ll a[4][4];
};
node shu,ans,mp;
ll n,mod;
node matrix(node x,node y)
{
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
mp.a[i][j]=0;
for(int p=1;p<=3;p++){
mp.a[i][j]=(mp.a[i][j]+x.a[i][p]*y.a[p][j]+mod)%mod;
}
}
}
return mp;
}
void work(ll k)
{
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
ans.a[i][j]=0;
}
}
for(int i=1;i<=3;i++){
ans.a[i][i]=1;
}
node t=shu;
while(k){
if(k&1){
ans=matrix(ans,t);
}
k>>=1;
t=matrix(t,t);
}
}
int main()
{
shu.a[1][1]=2;
shu.a[1][2]=1;
shu.a[1][3]=-2;
shu.a[2][1]=1;
shu.a[2][2]=shu.a[2][3]=0;
shu.a[3][1]=shu.a[3][3]=0;
shu.a[3][2]=1;
while(~scanf("%lld%lld",&n,&mod)){
if(n==1){
printf("%d\n",1%mod);
}else if(n==2){
printf("%d\n",2%mod);
}else if(n==3){
printf("%d\n",5%mod);
}else{
work(n-3);
printf("%lld\n",(ans.a[1][1]*5+ans.a[1][2]*2+ans.a[1][3])%mod);
}
}
return 0;
}