Elegant string
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 (random SIVE ). 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 ≤ 1018) 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" Case # X:", And X is the case number. Then output function (n, k) mod 20140518 in this case. sample input
21 17 6
Sample output
Case #1: 2Case #2: 818503
Source 2014 ACM-ICPC Beijing Invitational Programming Contest
Question: 0 ~ The numbers k construct a sequence with a length of N, so that any subsequence is not arranged by K and the number of seeds is required.
Idea: DP [I] [J] indicates that the length is I, followed by J different types of numbers, and there are two cases for filling in the following: 1. it is different from the last J. The K + 1-j filling method is used to obtain the status DP [I + 1] [J + 1]. 2. same as the previous J, obtain DP [I + 1] [1], DP [I + 1] [2]... DP [I + 1] [J]. Since N is very large and K is very small, we can use a matrix to accelerate it. By constructing a recursive relationship of one row, we can use a matrix to quickly power the matrix.
Code:
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <string>#include <map>#include <stack>#include <vector>#include <set>#include <queue>#define maxn 205#define MAXN 200005#define INF 0x3f3f3f3f#define mod 20140518#define eps 1e-6const double pi=acos(-1.0);typedef long long ll;using namespace std;ll n,k,ans;struct Matrix{ int row,col; ll v[15][15]; Matrix operator*(Matrix &tt) { int i,j,k; Matrix temp; temp.row=row; temp.col=tt.col; for(i=1; i<=row; i++) for(j=1; j<=tt.col; j++) { temp.v[i][j]=0; for(k=1; k<=col; k++) { temp.v[i][j]+=v[i][k]*tt.v[k][j]; temp.v[i][j]%=mod; } } return temp; }};Matrix pow_mod(Matrix x,ll i) // x^i{ Matrix tmp; tmp.row=x.row; tmp.col=x.col; memset(tmp.v,0,sizeof(tmp.v)); for(int j=1;j<=x.row;j++) tmp.v[j][j]=1; while(i) { if(i&1) tmp=tmp*x; x=x*x; i>>=1; } return tmp;}void solve(){ int i,j; Matrix A,res,x; x.row=1; x.col=k; res.row=1; res.col=k; memset(x.v,0,sizeof(x.v)); x.v[1][1]=k+1; A.row=A.col=k; memset(A.v,0,sizeof(A.v)); for(i=1;i<=k;i++) { A.v[i-1][i]=k-i+2; for(j=i;j<=k;j++) { A.v[j][i]=1; } } res=pow_mod(A,n-1); res=x*res; ans=0; for(i=1;i<=k;i++) { ans+=res.v[1][i]; ans%=mod; }}int main(){ int i,j,test,ca=0; scanf("%d",&test); while(test--) { scanf("%lld%lld",&n,&k); solve(); printf("Case #%d: %lld\n",++ca,ans); } return 0;}
Bnu oj 34985 elegant string (matrix + dp)