0
点赞
收藏
分享

微信扫一扫

Reading comprehension HDU - 4990

​​http://acm.hdu.edu.cn/showproblem.php?pid=4990​​

遇事不决先打表

打完前几项发现奇数项满足 a[2*n+1]=4*a[2*n-1]+1 直接矩阵快速幂

偶数就求相邻奇数项 再乘二

#include <bits/stdc++.h>
using namespace std;
#define ll long long

ll mat[5][5],ans[5][5];
ll mod;
int n;

void getmul(ll a[][5],ll b[][5])
{
ll t[5][5];
int i,j,k;
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
t[i][j]=0;
for(k=1;k<=3;k++) t[i][j]=(t[i][j]+(a[i][k]*b[k][j])%mod)%mod;
}
}
memcpy(a,t,sizeof(t));
}

ll quickpow(int p)
{
ll res;
int i,j;
mat[1][1]=4,mat[1][2]=0,mat[1][3]=1;
mat[2][1]=0,mat[2][2]=4,mat[2][3]=1;
mat[3][1]=0,mat[3][2]=0,mat[3][3]=1;
memset(ans,0,sizeof(ans));
ans[1][1]=1,ans[2][2]=1,ans[3][3]=1;
while(p>0)
{
if(p%2) getmul(ans,mat);
getmul(mat,mat),p/=2;
}
res=(5ll*ans[1][1]+ans[1][2]+ans[1][3])%mod;
if(n%2==0) res=(2ll*res)%mod;
return res;
}

int main()
{
while(scanf("%d%lld",&n,&mod)!=EOF)
{
if(n==1) printf("%lld\n",1ll%mod);
else if(n==2) printf("%lld\n",2ll%mod);
else if(n==3) printf("%lld\n",5ll%mod);
else printf("%lld\n",quickpow((n+1)/2-2));
}
return 0;
}

/*
4 1000000007
5 1000000007
6 1000000007
7 1000000007
8 1000000007
9 1000000007
10 1000000007
1000000 1000000007
*/

 


举报

相关推荐

0 条评论