hdu4565 So Easy! 广义斐波那契+矩阵快速幂+共轭构造

该博客详细介绍了如何利用广义斐波那契数列和矩阵快速幂的方法来解决HDU 4565题目的求解过程。通过共轭构造,得出递推关系式C(n+1)=2aC(n)-(a^2-b)C(n-1),进而使用矩阵快速幂优化计算,以高效求解(x=(a+sqrt(b))向上取整的n次方模mod的结果。
摘要由CSDN通过智能技术生成

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


求x=(a+sqrt(b) )向上取整

求Sn=x^n %mod


 ----------------------

记(a+sqrt_b)n为An,(a-sqrt_b)n 为bn

那么Cn=An+Bn=(a+sqrt_b)n+(a−sqrt_b)n

因为A B共轭 所以C为整数(没去证明)

那么根据题目对b的限定,显然 Bn是0到1间的小数,又答案是向上取整

所以An就等于Cn,

然后去递推Cn

用Cn乘以((a+sqrt_b)+(a−sqrt_b))

展开最后得到


C(n+1)=2aC(n)−(a2−b)C(n−1)

然后构造矩阵快速幂做即可

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;

const int N = 2;
long long  mod=1e9+7;
struct Matrix
{
    long long mat[N][N];
} ;
Matrix unit_matrix ;
long long n;
const long long  k=2;

Matrix mul(Matrix a, Matrix b) //矩阵相乘
{
    Matrix res;
    for(int i = 0; i < k; i++)
        for(int j = 0; j < k; j++)
        {
            res.mat[i][j] = 0;
            for(int t = 0; t < k; t++)
            {
                res.mat[i][j] += a.mat[i][t] * b.mat[t][j];
                res.mat[i][j] %= mod;
            }
        }

    return res;
}

Matrix pow_matrix(Matrix a, long long m)  //矩阵快速幂
{
    Matrix res = unit_matrix;
    while(m != 0)
    {
        if(m & 1)
            res = mul(res, a);
        a = mul(a, a);
        m >>= 1;
    }
    return res;
}
    long long a,b;
Matrix get(long long n)
{
    Matrix ori;
    memset(ori.mat,0,sizeof ori.mat);
    ori.mat[0][0]=ceil((a+sqrt(1.0*b))*(a+sqrt(1.0*b)));
    ori.mat[0][0]%=mod;
    ori.mat[0][1]=ceil(a+sqrt(1.0*b) );
    ori.mat[0][1]%=mod;
    Matrix c;
    c.mat[0][0]=2*a%mod;
    c.mat[0][1]=1;//b-a*a;
    c.mat[1][0]=(b-a*a)%mod;
    c.mat[1][0]=(c.mat[1][0]+mod)%mod;;
    c.mat[1][1]=0;
    Matrix ans = pow_matrix(c, n-1 );
    ans = mul(ori,ans);
    return ans;
}
int main()
{
    int  i, j, t;
    //初始化单位矩阵            //类似快速幂的 ans=1; 如今是ans=单位矩阵
    for(i = 0; i < k; i++)
        for(j = 0; j < k; j++)
            unit_matrix.mat[i][j] = 0;
    for(i = 0; i < k; i++)  unit_matrix.mat[i][i] = 1;
    while(scanf("%lld",&a)!=EOF)
    {
        scanf("%lld%lld%lld,",&b,&n,&mod);
        Matrix ans=get(n);
        printf("%lld\n", ans.mat[0][1]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值