线性递推式(外挂)
Posted yZi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线性递推式(外挂)相关的知识,希望对你有一定的参考价值。
传入前几项,输出低n项的值
1 #include <cstdio> 2 #include <cstring> 3 #include <cmath> 4 #include <algorithm> 5 #include <vector> 6 #include <string> 7 #include <map> 8 #include <set> 9 #include <cassert> 10 using namespace std; 11 #define rep(i,a,n) for (int i=a;i<n;i++) 12 #define per(i,a,n) for (int i=n-1;i>=a;i--) 13 #define pb push_back 14 #define mp make_pair 15 #define all(x) (x).begin(),(x).end() 16 #define fi first 17 #define se second 18 #define SZ(x) ((int)(x).size()) 19 typedef vector<int> VI; 20 typedef long long ll; 21 typedef pair<int,int> PII; 22 const ll mod=1000000007; 23 ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;} 24 // head 25 26 int _,n; 27 namespace linear_seq { 28 const int N=10010; 29 ll res[N],base[N],_c[N],_md[N]; 30 31 vector<int> Md; 32 void mul(ll *a,ll *b,int k) { 33 rep(i,0,k+k) _c[i]=0; 34 rep(i,0,k) if (a[i]) rep(j,0,k) _c[i+j]=(_c[i+j]+a[i]*b[j])%mod; 35 for (int i=k+k-1;i>=k;i--) if (_c[i]) 36 rep(j,0,SZ(Md)) _c[i-k+Md[j]]=(_c[i-k+Md[j]]-_c[i]*_md[Md[j]])%mod; 37 rep(i,0,k) a[i]=_c[i]; 38 } 39 int solve(ll n,VI a,VI b) { // a 系数 b 初值 b[n+1]=a[0]*b[n]+... 40 // printf("%d\n",SZ(b)); 41 ll ans=0,pnt=0; 42 int k=SZ(a); 43 assert(SZ(a)==SZ(b)); 44 rep(i,0,k) _md[k-1-i]=-a[i];_md[k]=1; 45 Md.clear(); 46 rep(i,0,k) if (_md[i]!=0) Md.push_back(i); 47 rep(i,0,k) res[i]=base[i]=0; 48 res[0]=1; 49 while ((1ll<<pnt)<=n) pnt++; 50 for (int p=pnt;p>=0;p--) { 51 mul(res,res,k); 52 if ((n>>p)&1) { 53 for (int i=k-1;i>=0;i--) res[i+1]=res[i];res[0]=0; 54 rep(j,0,SZ(Md)) res[Md[j]]=(res[Md[j]]-res[k]*_md[Md[j]])%mod; 55 } 56 } 57 rep(i,0,k) ans=(ans+res[i]*b[i])%mod; 58 if (ans<0) ans+=mod; 59 return ans; 60 } 61 VI BM(VI s) { 62 VI C(1,1),B(1,1); 63 int L=0,m=1,b=1; 64 rep(n,0,SZ(s)) { 65 ll d=0; 66 rep(i,0,L+1) d=(d+(ll)C[i]*s[n-i])%mod; 67 if (d==0) ++m; 68 else if (2*L<=n) { 69 VI T=C; 70 ll c=mod-d*powmod(b,mod-2)%mod; 71 while (SZ(C)<SZ(B)+m) C.pb(0); 72 rep(i,0,SZ(B)) C[i+m]=(C[i+m]+c*B[i])%mod; 73 L=n+1-L; B=T; b=d; m=1; 74 } else { 75 ll c=mod-d*powmod(b,mod-2)%mod; 76 while (SZ(C)<SZ(B)+m) C.pb(0); 77 rep(i,0,SZ(B)) C[i+m]=(C[i+m]+c*B[i])%mod; 78 ++m; 79 } 80 } 81 return C; 82 } 83 int gao(VI a,ll n) { 84 VI c=BM(a); 85 c.erase(c.begin()); 86 rep(i,0,SZ(c)) c[i]=(mod-c[i])%mod; 87 return solve(n,c,VI(a.begin(),a.begin()+SZ(c))); 88 } 89 }; 90 91 int main(){ 92 //for (scanf("%d",&_);_;_--) { 93 while(scanf("%d",&n)!=EOF){ 94 printf("%d\n",linear_seq::gao(VI{1,2,4,7,13,24},n-1)); 95 } 96 //} 97 }
以上是关于线性递推式(外挂)的主要内容,如果未能解决你的问题,请参考以下文章