hdu4565 So Easy! 廣義斐波那契+矩陣快速冪+共軛構造

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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章