首页 > 代码库 > bnu oj 34985 Elegant String (矩阵+dp)

bnu oj 34985 Elegant String (矩阵+dp)

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 (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 ≤ 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 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

Source

2014 ACM-ICPC Beijing Invitational Programming Contest


题意:
用0~k这几个数字构造一个长度为n的序列,使得任意一个子序列都不是k的排列,求种数。

思路:
dp[i][j]表示长度为i,后面有j个不同的种数,填充下一个有两种情况:
1.与后j个都不相同,有k+1-j种填法,得到状态dp[i+1][j+1]。
2.与后j个某个相同,得到dp[i+1][1]、dp[i+1][2]...dp[i+1][j]。
由于n很大,k很小,所以可以用矩阵来加速,构造一行一行的递推关系就可以矩阵快速幂了。

代码:
#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-6
const 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 (矩阵+dp)