HDU - 4565_So Easy!_共轭构造&&矩阵快速幂

题意

A sequence S n is defined as:
这里写图片描述
Where a, b, n, m are positive integers.┌x┐is the ceil of x. For example, ┌3.14┐=4. You are to calculate S n.
There are several test cases, each test case in one line contains four positive integers: a, b, n, m. Where 0< a, m < 2 15, (a-1) 2< b < a 2, 0 < b, n < 2 31.The input will finish with the end of file.

思路

((a+(根号b))的n次方) 必有 X + Y * (根号b) 的形式。
X 和 Y 可以应用矩阵快速幂求得。关键是 Y * (根号b) 向上取整的问题。
推导如下:
这里写图片描述

链接

https://vjudge.net/contest/176567#problem/C

代码

#include<cstdio>
#include<iostream>
#include<vector>

using namespace std;

typedef long long LL;
typedef vector<LL> vec;
typedef vector<vec> mat;

LL a, b, n, m;
LL mod;

mat mul(mat A, mat B)
{
    mat C(A.size(), vec(B[0].size()));

    for(int i= 0; i< A.size(); i++)
        for(int k= 0; k< B.size(); k++)
            for(int j= 0; j< B[0].size(); j++)
                C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % mod;

    return C;
}

mat pow(mat A, int n)
{
    mat B(A.size(), vec(A.size()));
    for(int i= 0; i< A.size(); i++)
        B[i][i] = 1;

    while(n > 0)
    {
        if(n & 1) B = mul(B, A);
        A = mul(A, A);
        n >>= 1;
    }

    return B;
}

int main()
{
    //freopen("in.txt", "r", stdin);

    while(scanf("%lld %lld %lld %lld", &a, &b, &n, &m) != EOF)
    {
        mat A(2, vec(2));
        mat B(2, vec(1));

        A[0][0] = a, A[0][1] = b, A[1][0] = 1, A[1][1] = a;
        B[0][0] = a, B[1][0] = 1;

        mod = m;

        A = pow(A, n - 1);
        B = mul(A, B);

        cout << 2 * B[0][0] % m << endl;
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值