E. Elegant String

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值