1. 程式人生 > >Gauss Fibonacci HDU - 1588 等比矩陣列求和

Gauss Fibonacci HDU - 1588 等比矩陣列求和

txt nbsp const while atp n) algo () operator

二分求和
或者矩陣套矩陣
|A E| ^n = |A^n E+...+A^(n-1)|
|0 E| |0 E |
https://cn.vjudge.net/solution/9721123
這個代碼我卻不懂了= =



#include <stdio.h> #include <cstring> #include <algorithm> #include <queue> #include <math.h> #include <iostream> using namespace std; #define LL long long const
int maxn=(int)1e5+5; LL MOD=8000; int n; struct mat{ LL a[2][2]; mat(){ memset(a,0,sizeof a); } mat operator *(const mat &q){ mat t; for(int i=0;i<n;i++) for(int j=0;j<n;j++ ){ LL w=0; for(int k=0;k<n;k++)w=(w+a[i][k]*q.a[k][j])%MOD; t.a[i][j]
=w; } return t; } mat operator +(const mat& q){ mat t;memset(t.a,0,sizeof t.a); for(int i=0;i<n;i++) for(int j=0;j<n;j++){ t.a[i][j]=(a[i][j]+q.a[i][j])%MOD; } return t; } void initE(){ a[1][0]=a[0][1]=0
;a[1][1]=a[0][0]=1; } void initFib(){ for(int i=0;i<n;i++)for(int j=0;j<n;j++)a[i][j]=1;a[1][1]=0; } void in(){ for(int i=0;i<n;i++) for(int j=0;j<n;j++)scanf("%lld",&a[i][j]); } void print(){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++)printf("%lld ",a[i][j]);printf("\n"); } } }; LL k,b,N; mat quickmatpower(mat a ,LL k){ mat res;res.initE(); while(k>0){ if(k&1)res=res*a; a=a*a; k>>=1LL; } return res; } LL quickpower(LL a,LL k){ LL res=1; while(k>0){ if(k&1)res=res*a; a=a*a; k>>=1LL; } return res; } mat calsum(mat a,LL k){ mat E;E.initE(); if(k==1) return a; if(k%2==0){ return calsum(a,k/2)*(E+quickmatpower(a,k/2)); } return calsum(a,k/2)*(E+quickmatpower(a,k/2))+quickmatpower(a,k); } LL work(){ mat f;f.initFib();mat E;E.initE(); return (quickmatpower(f,b)*((E+calsum(quickmatpower(f,k),N-1)))).a[0][1]; } int main() { #ifdef shuaishuai freopen("C:\\Users\\hasee\\Desktop\\a.txt","r",stdin); // freopen("C:\\Users\\hasee\\Desktop\\b.txt","w",stdout); #endif n=2; while(~scanf("%lld%lld%lld%lld",&k,&b,&N,&MOD)){ printf("%lld\n",work()); } return 0; }

Gauss Fibonacci HDU - 1588 等比矩陣列求和