【构造共轭函数+矩阵快速幂】HDU 4565 So Easy! (2013 长沙赛区邀请赛)

时间:2024-10-16 20:07:14

【解题思路】

给一张神图,推理写的灰常明白了,关键是构造共轭函数,这一点实在是要有数学知识的理论基础,推出了递推式,接下来就是矩阵的快速幂了。

神图:【构造共轭函数+矩阵快速幂】HDU 4565 So Easy! (2013 长沙赛区邀请赛)

给个大神的链接:构造类斐波那契数列的矩阵快速幂

/*
* Problem: HDU No.4565
* Running time: 62MS
* Complier: G++
* Author: javaherongwei
* Create Time: 9:55 2015/9/21 星期一
*/ #include <bits/stdc++.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm> using namespace std;
typedef long long LL;
const LL siz=; // max size of the matrix,
#define MODD(a,b) (((a%b)+b)%b) LL A,B,N,M,ret;
struct mut
{
LL mat[siz][siz];
mut(){
memset(mat,,sizeof(mat));
}
void init(LL a,LL b,LL c,LL d){
mat[][]=a;mat[][]=b;
mat[][]=c;mat[][]=d;
}
mut operator *(const mut &c)
{
mut res;
for(int i=; i<siz; ++i){
for(int k=; k<siz; ++k){
for(int j=; j<siz; ++j){
res.mat[i][j]=MODD(res.mat[i][j]+mat[i][k]*c.mat[k][j],M);
}
}
}
return res;
}
}AC; mut poww(LL n)
{
mut ans;
ans.init(,,,);
while(n){
if(n&) ans=ans*AC;
n>>=;
AC=AC*AC;
}
return ans;
} int main()
{
while(~scanf("%lld %lld %lld %lld",&A,&B,&N,&M)){
if(N<=){
printf("%lld\n",*A%M);
}
else{
AC.init(*A,B-A*A,,);
mut ans=poww(N-);
printf("%lld\n",MODD(*A%M*ans.mat[][]+*ans.mat[][],M));
}
} return ;
}