HDU

来源:互联网 发布:数组tostring 编辑:程序博客网 时间:2024/06/17 07:38

题意

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;}