递推式显然f[n]=p*f[n-1]-q*f[n-2],直接快速幂即可,只不过这题输入有坑。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
typedef LL matrix[3][3];
LL p,q;
int n;
void mat_mul(matrix A,matrix B,matrix res)
{
matrix C;
memset(C,0,sizeof(C));
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
C[i][j]+=A[i][k]*B[k][j];
memcpy(res,C,sizeof(C));
}
void mat_pow(matrix A,int n,matrix res)
{
matrix a,r;
memset(r,0,sizeof(r));
memcpy(a,A,sizeof(a));
for(int i=0;i<2;i++) r[i][i]=1;
while(n)
{
if(n&1) mat_mul(r,a,r);
n>>=1;
mat_mul(a,a,a);
}
memcpy(res,r,sizeof(r));
}
int main()
{
while(scanf("%lld%lld%d",&p,&q,&n)==3)
{
if(n==0)
{
puts("2");
continue;
}
matrix A,B;
A[0][0]=0,A[0][1]=1,A[1][0]=-q,A[1][1]=p;
mat_pow(A,n-1,B);
LL ans=B[0][0]*p+B[0][1]*(p*p-2*q);
printf("%lld\n",ans);
}
return 0;
}