主要思路
70 pts 思路
无非就是按照递推式来一步步递推。这里不详细讲了。
70 pts代码
#include<iostream>
using namespace std;
int a[2147483648];
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr),cout.tie(nullptr);
int p,q,n,m;
cin>>p>>q>>a[1]>>a[2]>>n>>m;
for(int i=3;i<=n;i++){
a[i]=(p*a[i-1]+q*a[i-2])%m;
}
cout<<a[n];
return 0;
}100 pts 思路
我们考虑矩阵加速。根据正常的 Fibonacci,我们需要求出一个矩阵 。跟 Fibonacci 一样,我们需要根据 来推出 。我们想想,如何用 来推出 呢?其实很简单。新矩阵中的 可以直接从原来的矩阵给保留了下来,所以不难推出转移矩阵的第二列为 。对于 ,我们已经知道 ,所以转移矩阵的第一列就应该为 。所以整个转移矩阵就应该为 。那么,这道题的答案就出来了:。知道这个这道题就可以直接秒了!
WARNING
要特判,不然会被 hack 掉。
100 pts代码
#include<bits/stdc++.h>
using namespace std;
struct node{
int arr[2][2];
node(){memset(arr,0,sizeof arr);}
}f,dw;
int m;
node operator*(const node& x,const node& y){
node t;
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
t.arr[i][j]=0;
for(int k=0;k<2;k++){
t.arr[i][j]=(t.arr[i][j]+1ll*x.arr[i][k]*y.arr[k][j])%m;
}
}
}
return t;
}
node qpow(node a,int b){
node ans;
ans.arr[0][0]=ans.arr[1][1]=1;
while(b){
if(b&1)ans=ans*a;
a=a*a;
b>>=1;
}
return ans;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr),cout.tie(nullptr);
int p,q,n;
cin>>p>>q>>f.arr[0][1]>>f.arr[0][0]>>n>>m;//这里注意先读入[0][1]再读入[0][0]!!!
if(n==1){
cout<<f.arr[0][1]%m;
return 0;
}else if(n==2){
cout<<f.arr[0][0]%m;
return 0;
}
dw.arr[0][0]=p,dw.arr[0][1]=1,
dw.arr[1][0]=q,dw.arr[1][1]=0;
dw=qpow(dw,n-2);
node ans=f*dw;
cout<<ans.arr[0][0]%m;
return 0;
}