参考题解:hdu 4565 So Easy! (共轭构造+矩阵快速幂)
题意:求值。
思路:根据可构造共轭方程,因为共轭,所以一定是整数,而且由知,所以可以忽略不计。
进行一些变换:
这样问题就转化成了快速求斐波那契数列第n项的问题。
/****************************************************
>Created Date: 2015-10-01-13.34.56
>My Soul, Your Beats!
****************************************************/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cmath>
#include <iostream>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <algorithm>
using namespace std;
typedef long long LL;
const int INF = 1 << 30;
const long long LINF = 1LL << 50;
const int M = 1e5 + 10;
const double PI = acos(-1.0);
const double eps = 1e-6;
int MOD, top;
struct Matrix{
int n, m;
LL a[2][2];
void clear(){
n = m = 0;
memset(a, 0, sizeof a);
}
Matrix operator *(const Matrix &b) const {
Matrix tmp;
tmp.clear();
tmp.n = n, tmp.m = b.m;
for(int i = 0; i < n; i++) {
for(int j = 0; j < b.m; j++){
for(int k = 0; k < m; k++){
tmp.a[i][j] = (tmp.a[i][j] + a[i][k] * b.a[k][j]) % MOD;
}
}
}
return tmp;
}
};
Matrix pow(Matrix a, int b){
Matrix ret;
ret.clear();
ret.m = ret.n = 2;
ret.a[0][0] = ret.a[1][1] = 1;
while(b){
if(b & 1){
ret = ret * a;
}
a = a * a;
b >>= 1;
}
return ret;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("in.in", "r", stdin);
#endif // ONLINE_JUDGE
LL a, b, p;
while(~scanf("%lld %lld %lld %d", &a, &b, &p, &MOD)){
Matrix mat, f;
mat.n = mat.m = 2;
mat.a[0][0] = a * 2 % MOD;
mat.a[0][1] = ((b - a * a) % MOD + MOD) % MOD;
mat.a[1][0] = 1;
mat.a[1][1] = 0;
f.n = 2, f.m = 1;
f.a[0][0] = (a + (int)ceil(sqrt(b))) % MOD;
f.a[1][0] = 2 % MOD;
Matrix mm = pow(mat, p - 1);
Matrix ans = mm * f;
printf("%lld\n", ans.a[0][0]);
}
return 0;
}