您的位置:首页 > 其它

hdu 4549 矩阵快速幂

2015-06-14 10:49 267 查看
题意:

M斐波那契数列F
是一种整数数列,它的定义如下:

F[0] = a
F[1] = b
F
= F[n-1] * F[n-2] ( n > 1 )

现在给出a, b, n,你能求出F
的值吗?

链接:点我

这题的话,看a ,b 的指数,刚好可以使用斐波那契数列求解。

然后用矩阵做。

A^B %C 这题的C是质素,而且A,C是互质的。
所以直接A^(B%(C-1)) %C

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
using namespace std;
#define MOD 1000000007
#define pb(a) push_back(a)
const int INF=0x3f3f3f3f;
const double eps=1e-5;
typedef long long ll;
#define cl(a) memset(a,0,sizeof(a))
#define ts printf("*****\n");
const int MAXN=30010;
int n,m,tt,cnt;
struct Matrix
{
long long mat[2][2];
};
Matrix mul(Matrix a,Matrix b)
{
Matrix ret;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
{
ret.mat[i][j]=0;
for(int k=0;k<2;k++)
{
ret.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
ret.mat[i][j]%=(MOD-1);
}
}
return ret;
}
Matrix pow_M(Matrix a,int n)
{
Matrix ret;
memset(ret.mat,0,sizeof(ret.mat));
ret.mat[0][0]=ret.mat[1][1]=1;
Matrix temp=a;
while(n)
{
if(n&1)ret=mul(ret,temp);
temp=mul(temp,temp);
n>>=1;
}
return ret;
}
long long pow_m(long long a,long long n)
{
long long ret=1;
long long temp=a%MOD;
while(n)
{
if(n&1)
{
ret*=temp;
ret%=MOD;
}
temp*=temp;
temp%=MOD;
n>>=1;
}
return ret;
}
int main()
{
int i,j,k;
#ifndef ONLINE_JUDGE
freopen("1.in","r",stdin);
#endif
int a,b;
Matrix aa;
aa.mat[0][0]=0;
aa.mat[0][1]=aa.mat[1][0]=aa.mat[1][1]=1;
while(~scanf("%d%d%d",&a,&b,&n))
{
Matrix bb=pow_M(aa,n);
int ans=(pow_m(a,bb.mat[0][0])*pow_m(b,bb.mat[1][0]))%MOD;
printf("%d\n",ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: