題目鏈接:點我
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爲未知數,那麼
又因爲我們知道
代碼:
#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;
}