hdu 4565 So Easy! 共轭构造+斐波那契矩阵加速

hdu 4565

参考题解:hdu 4565 So Easy! (共轭构造+矩阵快速幂)

题意:求值

思路:根据可构造共轭方程,因为共轭,所以一定是整数,而且由,所以可以忽略不计。

进行一些变换:

这样问题就转化成了快速求斐波那契数列第n项的问题。

/****************************************************
  >Created Date: 2015-10-01-13.34.56
  >My Soul, Your Beats!
****************************************************/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cmath>
#include <iostream>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <algorithm>
using namespace std;

typedef long long LL;

const int INF = 1 << 30;
const long long  LINF = 1LL << 50;
const int M = 1e5 + 10;
const double PI = acos(-1.0);
const double eps = 1e-6;
int MOD, top;
struct Matrix{
    int n, m;
    LL a[2][2];
    void clear(){
        n = m = 0;
        memset(a, 0, sizeof a);
    }
    Matrix operator *(const Matrix &b) const {
        Matrix tmp;
        tmp.clear();
        tmp.n = n, tmp.m = b.m;
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < b.m; j++){
                for(int k = 0; k < m; k++){
                    tmp.a[i][j] = (tmp.a[i][j] + a[i][k] * b.a[k][j]) % MOD;
                }
            }
        }
        return tmp;
    }
};
Matrix pow(Matrix a, int b){
    Matrix ret;
    ret.clear();
    ret.m = ret.n = 2;
    ret.a[0][0] = ret.a[1][1] = 1;
    while(b){
        if(b & 1){
            ret = ret * a;
        }
        a = a * a;
        b >>= 1;
    }
    return ret;
}
int main(){
    #ifndef ONLINE_JUDGE
        freopen("in.in", "r", stdin);
    #endif // ONLINE_JUDGE
    LL a, b, p;
    while(~scanf("%lld %lld %lld %d", &a, &b, &p, &MOD)){
        Matrix mat, f;
        mat.n = mat.m = 2;
        mat.a[0][0] = a * 2 % MOD;
        mat.a[0][1] = ((b - a * a) % MOD + MOD) % MOD;
        mat.a[1][0] = 1;
        mat.a[1][1] = 0;
        f.n = 2, f.m = 1;
        f.a[0][0] = (a + (int)ceil(sqrt(b))) % MOD;
        f.a[1][0] = 2 % MOD;
        Matrix mm = pow(mat, p - 1);
        Matrix ans = mm * f;
        printf("%lld\n", ans.a[0][0]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值