So Easy! HDU - 4565 矩阵快速幂

题目链接:点我


 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.
  You, a top coder, say: So easy!

 这里写图片描述
Input

  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.

Output

  For each the case, output an integer S n.

Sample Input

2 3 1 2013
2 3 2 2013
2 2 1 2013

Sample Output

4
14
4

题意:

如同题目公式描述的那样.

思路:
矩阵快速幂,
我们设 x, y为未知数,那么 (a+b)n = x + y * b 的形式,其他x, y为整数,又因为 (a1)2 < b < a2 ,那么a - 1 <b< a,于是ceil( b ) = a; 于是 (ab)n< 1,而它与 (a+b)n 相加后展开式中会抵消掉待有根号的项, 而我们又知道 (a+b)n+1 = xn+1+yn+1b = ( xn+ynb ) *( a+b ) = (xna+ynb)+(ayn+xn)b 由此我们可以构造出递推式, xn+1=xna+ynb , yn+1=xn+yna ;
又因为我们知道 (a+b)n+(ab)n=2xn , 而且 (ab)n< 1,所以ceil( (a+b)n ) = 2xn ,

代码:

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

typedef long long LL;
LL a, b,n, m;
struct mat{
    LL a[3][3];
    mat(){memset(a, 0, sizeof(a)); }
    mat operator *(const mat q){
        mat c;
        for(int i = 1; i <= 2; ++i)
            for(int j = 1; j <= 2; ++j)
            if(a[i][j])
        for(int k = 1; k <= 2; ++k){
            c.a[i][k] += a[i][j] * q.a[j][k];
            if (c.a[i][k] >= m) c.a[i][k] %= m;
        }return c;
    }
};

mat qpow(mat x, LL n){
    mat ans;
    ans.a[1][1] = ans.a[2][2] = 1;
    while(n){
        if (n&1) ans = ans * x;
        x = x * x;
        n >>= 1;
    }return ans;
}


int main(){
    while(scanf("%lld %lld %lld %lld", &a, &b, &n, &m) != EOF){
        mat ans;
        a = a % m;
        b = b %m;
        ans.a[1][1] = ans.a[2][2] =a;
        ans.a[1][2] =  b;
        ans.a[2][1] = 1;
        ans = qpow(ans, n);
        LL sum = ans.a[1][1];
        sum = (sum * 2) % m;
        printf("%lld\n",sum);
    }return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值