
f0=0,f1=1,fi=fi-1+fi-2(i>=2),求fn mod p
对于100%的数据,0 < t < 10^5,0< n < 10^9,0 < p < 10^9
题意是求裴波那契数列的第N项,针对此题较大的数据,采用矩阵运算来加速
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include<cstring> using namespace std; int i,j,n,t,p; struct { long long a[3][3]; matrix(){ memset(a,0,sizeof a); } void operator *=(const matrix &x){ matrix ans=matrix(); for (int i=1;i<=2;i++) for (int j=1;j<=2;j++) ans.a[i][j]=(a[i][1]*x.a[1][j]+a[i][2]*x.a[2][j])%p; *this=ans; } void clear(){ a[1][1]=a[1][2]=a[2][1]=1%p; a[2][2]=0; } }x=matrix(),ans=matrix(); void work(){ while (n){ if (n&1) ans*=x; x*=x; n/=2; } } int main(){ freopen("eins.in","r",stdin); freopen("eins.out","w",stdout); scanf("%d",&t); while (t--){ scanf("%d%d",&n,&p); if (n==0) {printf("0n"); continue;} ans.clear(); x.clear(); n--; work(); printf("%lldn",ans.a[2][1]); } return 0; }
|
链接
COGS
近期评论