矩阵快速幂专题+题解: 点击打开链接
hdu 4565 代码:
#include<stdio.h>
#include<iostream>
using namespace std;
#define ll long long
ll mod;
struct Ju
{
ll x[4][4];
};
Ju operator *(const Ju& a,const Ju& b)
{
Ju c;
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
c.x[i][j]=0;
for(int k=0;k<2;k++)
{
c.x[i][j]+=(a.x[i][k]*b.x[k][j])%mod;
c.x[i][j]%=mod;
}
}
}
return c;
}
Ju pow(Ju a,ll n)
{
Ju one;
one.x[0][0]=one.x[1][1]=1;
one.x[0][1]=one.x[1][0]=0;
while(n)
{
if(n&1)
{
one=one*a;
}
a=a*a;
n/=2;
}
return one;
}
int main()
{
ll a,b,n,m;
while(~scanf("%lld%lld%lld%lld",&a,&b,&n,&m))
{
mod=m;
Ju A;
A.x[0][0]=a;
A.x[0][1]=b;
A.x[1][0]=1;
A.x[1][1]=a;
Ju ans=pow(A,n-1);
ll he=0;
he+=(ans.x[0][0]*a)%mod;
he+=ans.x[0][1]%mod;
printf("%lld\n",(2*he)%mod);
}
}
hdu 2256 代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
const int mod=1024;
struct Ju
{
int x[4][4];
};
Ju operator *(Ju a,Ju b)
{
Ju c;
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
c.x[i][j]=0;
for(int k=0;k<2;k++)
{
c.x[i][j]+=(a.x[i][k]*b.x[k][j])%mod;;
c.x[i][j]%=mod;
}
}
}
return c;
}
Ju pow(Ju a,int n)
{
Ju one;
for(int i=0; i<2; i++)
{
for(int j=0; j<2; j++)
{
if(i==j)
one.x[i][j]=1;
else
one.x[i][j]=0;
}
}
while(n)
{
if(n&1)
{
one=one*a;
}
a=a*a;
n/=2;
}
return one;
}
int main()
{
int t;
while(~scanf("%d",&t))
{
int n;
while(t--)
{
Ju a;
a.x[0][0]=5;
a.x[0][1]=12;
a.x[1][0]=2;
a.x[1][1]=5;
scanf("%d",&n);
Ju ans=pow(a,n);
printf("%d\n",(ans.x[0][0]*2-1)%mod);
}
}
}