P1349 广义斐波那契数列——矩阵加速——题解
longyitongxue · · 题解
题目传送门
主要思路
70 pts 思路
无非就是按照递推式来一步步递推。这里不详细讲了。
::::info[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,我们需要求出一个矩阵
::::warning{open} 要特判,不然会被 hack 掉。 ::::
::::success[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;
}
::::