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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章