HDU 4565 (数学推导 矩阵快速幂)

So Easy!

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3517    Accepted Submission(s): 1136


Problem Description
  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! 
HDU 4565 (数学推导 矩阵快速幂)_第1张图片
 

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
 


根据b的范围可知(a-sqrt (b))^n属于(0,1),因为需要求原始的ceil,所以可以把这个数转

化为小数部分和整数部分。

首先先推出一个递推式:

HDU 4565 (数学推导 矩阵快速幂)_第2张图片

然后后面的部分就可以用矩阵求了。

然后这个Fn其实就是所求的n次,因为向上取整,而这个Fn本身是一个整数,后半部分是

小于1的,所以前面部分向上取整恰好就是Fn。

#include <iostream>
#include <algorithm>
#include <string.h>
#include <stdio.h>
#include <map>
#include <vector>
#include <math.h>
#include <queue>
using namespace std;
#define maxn 21111

long long a, b, mod, n;
struct m {
    long long a[2][2];
    m operator * (m gg) {
        m ans;
        memset (ans.a, 0, sizeof ans.a);
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                for (int l = 0; l < 2; l++) {
                    ans.a[i][j] += a[i][l]*gg.a[l][j];
                    ans.a[i][j] %= mod;
                }
            }
        }
        return ans;
    }
    void show () {
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++)
                cout << a[i][j] << " ";
            cout << endl;
        }
    }
};

m qpow (m a, long long k) { //cout << k << ".." << endl;
    m ans;
    int i, j;
    for(i = 0; i < 2; ++i)
        for(j = 0; j < 2; ++j)
            ans.a[i][j] = (i == j ? 1 : 0);
    //ans.show ();
    for(; k; k >>= 1) {
        if(k&1) ans = ans*a;
        a = a*a;
    }
    //ans.show ();
    return ans;
}

int main () {
    //freopen ("in.txt", "r", stdin);
    while (scanf ("%lld%lld%lld%lld", &a, &b, &n, &mod) == 4) {
        m ans;
        ans.a[0][0] = 2*a%mod, ans.a[0][1] = 1, ans.a[1][0] = ((b-a*a)%mod+mod)%mod,
         ans.a[1][1] = 0;
        //ans.show ();
        ans = qpow (ans, n-1);
        //ans.show ();
        long long num = ans.a[0][0]*a%mod*2%mod + ans.a[1][0]*2%mod;
        num %= mod;
        printf ("%lld\n", num);
    }
    return 0;
}


你可能感兴趣的:(HDU 4565 (数学推导 矩阵快速幂))