杜教板子(BM) 线性递推式
解决传统线性递推式神器
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 #include<bits/stdc++.h> 11 using namespace std; 12 #define rep(i,a,n) for (int i=a;i<n;i++) 13 #define per(i,a,n) for (int i=n-1;i>=a;i--) 14 #define pb push_back 15 #define mp make_pair 16 #define all(x) (x).begin(),(x).end() 17 #define fi first 18 #define se second 19 #define SZ(x) ((int)(x).size()) 20 typedef vector<int> VI; 21 typedef long long ll; 22 typedef pair<int,int> PII; 23 const ll mod=1000000007; 24 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;} 25 // head 26 27 int _,n; 28 namespace linear_seq { 29 const int N=10010; 30 ll res[N],base[N],_c[N],_md[N]; 31 32 vector<int> Md; 33 void mul(ll *a,ll *b,int k) { 34 rep(i,0,k+k) _c[i]=0; 35 rep(i,0,k) if (a[i]) rep(j,0,k) _c[i+j]=(_c[i+j]+a[i]*b[j])%mod; 36 for (int i=k+k-1;i>=k;i--) if (_c[i]) 37 rep(j,0,SZ(Md)) _c[i-k+Md[j]]=(_c[i-k+Md[j]]-_c[i]*_md[Md[j]])%mod; 38 rep(i,0,k) a[i]=_c[i]; 39 } 40 int solve(ll n,VI a,VI b) { // a 系数 b 初值 b[n+1]=a[0]*b[n]+... 41 // printf("%d\n",SZ(b)); 42 ll ans=0,pnt=0; 43 int k=SZ(a); 44 assert(SZ(a)==SZ(b)); 45 rep(i,0,k) _md[k-1-i]=-a[i];_md[k]=1; 46 Md.clear(); 47 rep(i,0,k) if (_md[i]!=0) Md.push_back(i); 48 rep(i,0,k) res[i]=base[i]=0; 49 res[0]=1; 50 while ((1ll<<pnt)<=n) pnt++; 51 for (int p=pnt;p>=0;p--) { 52 mul(res,res,k); 53 if ((n>>p)&1) { 54 for (int i=k-1;i>=0;i--) res[i+1]=res[i];res[0]=0; 55 rep(j,0,SZ(Md)) res[Md[j]]=(res[Md[j]]-res[k]*_md[Md[j]])%mod; 56 } 57 } 58 rep(i,0,k) ans=(ans+res[i]*b[i])%mod; 59 if (ans<0) ans+=mod; 60 return ans; 61 } 62 VI BM(VI s) { 63 VI C(1,1),B(1,1); 64 int L=0,m=1,b=1; 65 rep(n,0,SZ(s)) { 66 ll d=0; 67 rep(i,0,L+1) d=(d+(ll)C[i]*s[n-i])%mod; 68 if (d==0) ++m; 69 else if (2*L<=n) { 70 VI T=C; 71 ll c=mod-d*powmod(b,mod-2)%mod; 72 while (SZ(C)<SZ(B)+m) C.pb(0); 73 rep(i,0,SZ(B)) C[i+m]=(C[i+m]+c*B[i])%mod; 74 L=n+1-L; B=T; b=d; m=1; 75 } else { 76 ll c=mod-d*powmod(b,mod-2)%mod; 77 while (SZ(C)<SZ(B)+m) C.pb(0); 78 rep(i,0,SZ(B)) C[i+m]=(C[i+m]+c*B[i])%mod; 79 ++m; 80 } 81 } 82 return C; 83 } 84 int gao(VI a,ll n) { 85 VI c=BM(a); 86 c.erase(c.begin()); 87 rep(i,0,SZ(c)) c[i]=(mod-c[i])%mod; 88 return solve(n,c,VI(a.begin(),a.begin()+SZ(c))); 89 } 90 }; 91 92 int main() { 93 while (~scanf("%d",&n)) { 94 vector<int>v; 95 v.push_back(1); 96 v.push_back(2); 97 v.push_back(4); 98 v.push_back(7); 99 v.push_back(13); 100 v.push_back(24); 101 //VI{1,2,4,7,13,24} 102 printf("%d\n",linear_seq::gao(v,n-1)); 103 } 104 } 105 106 BM