一个字符串(仅包含0-k)的任何子串都不是 0-k 的某个全排列,求长度为n的该字符串的数量。
对于n很大的情况,一般是矩阵快速幂。矩阵快速幂的第一步就是找出递推公式。
设dp[i][j]表示长度为n的字符串,串末尾有j个数是不同的(j=k+1时不合法)。
当末尾为j-1个不同时,可以选择(k+1)-(j-1)种方案使得末尾有j个不同;
当末尾为j个不同时(2,1,2,...,j),可以选择1作为新末尾(2,1,2,...,j,1)使得末尾依然有j个不同;
当末尾有j+1个不同时(2,1,2,...,j+1),可以选择2作为新末尾(2,1,2,...,j+1,2)使得末尾变成j个不同;
...依次类推,有公式:
dp[i][j]=(k+2-j)*dp[i-1][j-1]+dp[i-1][j]+...dp[i-1][k];(j=k+1时不合法)
根据递推公式有矩阵转移方程:
dp=|1 1 1 ... 1 1| * dp
|k 1 1 ... 1 1|
|0 k 1 ... 1 1|
|... 1 1|
|0 0 0 ... k 1|
长度为1时,dp[1]=k+1种,其他为0,;最后答案是sum(dp[i]) i=1 to n
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
const int MOD=20140518,N=10;
#define mem(a,b) memset(a,b,sizeof a);
LL n;
int k;
struct Mat{
LL a[N][N];
Mat(){
mem(a,0);
}
void Unit(){
for(int i=0;i<N;i++) a[i][i]=1;
}
void Init(int k){
for(int i=0;i<k;i++)
for(int j=i;j<k;j++) a[i][j]=1;
for(int i=1;i<k;i++)
a[i][i-1]=k+1-i;
}
};
void add(LL &x,LL y){
x=(x+y)%MOD;
}
Mat mul(Mat x,Mat y){
Mat ret;
for(int i=0;i<k;i++){
for(int j=0;j<k;j++)
for(int t=0;t<k;t++)
add(ret.a[i][j],x.a[i][t] * y.a[t][j]);
}
return ret;
}
Mat pow(Mat x,LL cf){
Mat ret; ret.Unit();
while(cf){
if(cf&1) ret=mul(ret,x);
x=mul(x,x);
cf>>=1;
}
return ret;
}
LL dp[N];
LL solve(){
Mat a; a.Init(k);
Mat ret=pow(a,n-1);
LL rst=0;
for(int i=0;i<k;i++)
add(rst,ret.a[i][0] * dp[0]);
return rst;
}
int main(){
int tt,cas=1;
for(cin>>tt;cas<=tt;cas++){
cin>>n>>k;
mem(dp,0);
dp[0]=k+1;
printf("Case #%d: %lld\n",cas,solve());
}
return 0;
}
/*
3
1 2
2 2
3 2
____
3
9
21
*/