E. Elegant String
1000ms
1000ms
65536KB
64-bit integer IO format:
%lld Java class name:
Main
Font Size:
We define a kind of strings as elegant string: among all the substrings of an elegant string, none of them is a permutation of "0, 1,…, k".
Let function(n, k) be the number of elegant strings of length n which only contains digits from 0 to k (inclusive). Please calculate function(n, k).
Input
Input starts with an integer T (T ≤ 400), denoting the number of test cases.
Each case contains two integers, n and k. n (1 ≤ n ≤ 10
18) represents the length of the strings, and k (1 ≤ k ≤ 9) represents the biggest digit in the string.
Output
For each case, first output the case number as "
Case #x: ", and x is the case number. Then output function(n, k) mod 20140518 in this case.
Sample Input
2 1 1 7 6
Sample Output
Case #1: 2 Case #2: 818503
permutation:全排列
给个k=4的自动机图。
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; #define rep(i,s,t) for(int i=s;i<t;i++) #define clr(a) memset(a,0,sizeof(a)) typedef long long ll; const ll mod=20140518; const int N=12; int k,t; ll n; struct Ma{ ll a[N][N]; }D,E; inline Ma Mul(Ma a,Ma b){ Ma ans; rep(i,1,k+2) rep(j,1,k+2){ ans.a[i][j]=0; rep(r,1,k+2){ ans.a[i][j]=(ans.a[i][j]+a.a[i][r]*b.a[r][j])%mod; } } return ans; } inline ll Pow(ll a,ll b){ ll d=1,t=a; while(b){ if(b&1) d=d*t%mod; b>>=1; t=t*t%mod; } return d; } inline Ma Pow(Ma a,ll b){ Ma d=E,t=a; while(b){ if(b&1) d=Mul(d,t); b>>=1; t=Mul(t,t); } return d; } inline void Init(){ rep(i,1,k+2) rep(j,1,k+2) E.a[i][j]=(i==j); clr(D.a); rep(i,1,k+2){ if(i==1){ rep(j,1,k+1) D.a[i][j]=1; } else if(i==k+1){ D.a[i][k]=1; D.a[i][k+1]=k+1; } else{ rep(j,i,k+1) D.a[i][j]=1; D.a[i][i-1]=(k+1-(i-1)); } } } inline void Work(){ ll ans=Pow(k+1,n); D=Pow(D,n-1); ans-=D.a[k+1][1]*(k+1)%mod; printf("%lld\n",(ans+mod)%mod); } int main(){ scanf("%d",&t); rep(ca,1,t+1){ scanf("%lld%d",&n,&k); Init(); printf("Case #%d: ",ca); Work(); } return 0; }