The problem of violence Well, consider a lot of things.
First set f (x) is the expected number of steps x step from the finish to go, we can find:
1.x> time = k, x can be transferred to the index points are <x.
2.x <When k, x, or it may go back to the larger point index.
Because k very small, so we can put f (0) (apparently 0), f (1), f (2), ....., f (k-1) Gaussian elimination of violence out (this is not you We will try to be written for each equation x 0 <x <k out, then f (x) to the left the whole item, other items whole to the right, an equation can be obtained; this column k -1 equations, unknown exactly k-1, Gaussian elimination template).
2. So that we solved the case. 1. So for a lot of cases, we can use from pushing subscript 2 smaller f () to do matrix multiplication.
So that's two questions: first, then build a matrix Gaussian elimination, and then build a fast power matrix, the matrix vector multiply the last to do it again you can get the answer.
#include<bits/stdc++.h> #define ll long long using namespace std; const int N=23,ha=1000000007; inline int add(int x,int y){ x+=y; return x>=ha?x-ha:x;} inline void ADD(int &x,int y){ x+=y; if(x>=ha) x-=ha;} inline int ksm(int x,int y){ int an=1; for(;y;y>>=1,x=x*(ll)x%ha) if(y&1) an=an*(ll)x%ha; return an; } int k,inv,Inv,ans; ll n; struct node{ int a[N][N]; inline void clear(){ memset(a,0,sizeof(a));} inline void Base(){ clear(); for(int i=0;i<=k;i++) a[i][i]=1; } node operator *(const node &u)const{ node r; r.clear(); for(int l=0;l<=k;l++) for(int i=0;i<=k;i++) for(int j=0;j<=k;j++) ADD(r.a[i][j],a[i][l]*(ll)u.a[l][j]%ha); return r; } inline void build(){ clear(),a[k][k]=1; for(int i=1;i<k;i++){ a[i][k]=(i*2>k)?1:k*(ll)Inv%ha,a[i][i]=1; for(int j=1,to;j<=k;j++){ to=i-j; if(to<0) to=-to; if(to&&to!=i) ADD(a[i][to],ha-((i*2>k)?inv:Inv)); } } } inline void solve(){ for(int i=1,ne;i<k;i++){ for(int j=i;j<k;j++) if(a[j][i]){ ne=j; break;} if(ne!=i) for(int l=i;l<=k;l++) swap(a[ne][l],a[i][l]); int ni=ksm(a[i][i],ha-2),now; for(int j=i+1;j<k;j++){ now=ni*(ll)a[j][i]%ha; for(int l=i;l<=k;l++) ADD(a[j][l],ha-a[i][l]*(ll)now%ha); } } for(int i=k-1;i;i--){ for(int j=i+1;j<k;j++) ADD(a[i][k],ha-a[i][j]*(ll)a[j][k]%ha); a[i][k]=a[i][k]*(ll)ksm(a[i][i],ha-2)%ha; // printf("%d %d\n",i,a[i][k]); } } inline void init(){ clear(); for(int i=k-2;i>=0;i--) a[i+1][i]=1; for(int i=0;i<k;i++) a[i][k-1]=inv; a[k][k-1]=1,a[k][k]=1; } }A,X,ANS; int main(){ scanf("%lld%d",&n,&k),inv=ksm(k,ha-2),Inv=ksm(k-1,ha-2); if(k==1){ printf("%d\n",n%ha); return 0;} A.build(),A.solve(),X.init(); n-=k-1,ANS.Base (); for(;n;n>>=1,X=X*X) if(n&1) ANS=ANS*X; for(int i=0;i<=k;i++) ADD(ans,A.a[i][k]*(ll)ANS.a[i][k-1]%ha); printf("%d\n",ans); return 0; }