【bzoj1009】[HNOI2008]GT考試 矩陣+kmp+DP

來源:互聯網
上載者:User
Description

阿申準備報名參加GT考試,准考證號為N位元X1X2….Xn(0<=Xi<=9),他不希望准考證號上出現不吉利的數字。他的不吉利數學A1A2…Am(0<=Ai<=9)有M位,不出現是指X1X2…Xn中沒有恰好一段等於A1A2…Am. A1和X1可以為0 Input

第一行輸入N,M,K.接下來一行輸入M位的數。 100%資料N<=10^9,M<=20,K<=1000 40%資料N<=1000 10%資料N<=6 Output

阿申想知道不出現不吉利數位號碼有多少種,輸出模K取餘的結果. Sample Input

4 3 100 111
Sample Output
81
HINT Source

設dp[i][j]為第i個號碼匹配到第j個不吉利數位方案數。

顯然前i個號碼的尾碼構成了前j個不吉利數字,而dp[i][j]向i+1轉移相當於在尾碼後面新加一個字元,可以聯想到AC自動機,然而這個只有一個串所以kmp就足夠了。

設a[k][j]為k位後面加一個字母轉移到j的方案數,於是:

dp[i][j]=∑0<=k<=m−1dp[i−1][k]∗a[k][j] dp[i][j]=\sum_{0

我們發現k後面加一個字母轉移到j可以用kmp實現。

這個式子是線性,可以用矩陣最佳化。

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;typedef long long LL;const int SZ = 1000010;const int INF = 1000000010;int n,m,mod,nxt[233];char s[233];void getnxt(char s[]){    int l = strlen(s);    nxt[0] = nxt[1] = 0;    for(int i = 1;i < l;i ++)    {        int j = nxt[i];        while(j && s[i] != s[j]) j = nxt[j];        nxt[i + 1] = s[i] == s[j] ? j + 1 : 0;    }}struct matrix{    int n,m,num[30][30];    matrix(int a,int b) : n(a),m(b) {memset(num,0,sizeof(num));}};matrix operator *(const matrix &a,const matrix &b){    matrix ans(a.n,b.m);    for(int i = 0;i < ans.n;i ++)        for(int j = 0;j < ans.m;j ++)            for(int k = 0;k < a.m;k ++)                ans.num[i][j] = (ans.num[i][j] + (LL)a.num[i][k] * b.num[k][j] % mod) % mod;    return ans;}matrix ksm(matrix a,int b){    matrix ans(a.n,a.m);    for(int i = 0;i < ans.n;i ++)        ans.num[i][i] = 1;    while(b)    {        if(b & 1) ans = ans * a;        a = a * a;        b >>= 1;    }    return ans;}int main(){    scanf("%d%d%d%s",&n,&m,&mod,s);    getnxt(s);    matrix f(m,m);    for(int i = 0;i < m;i ++)    {        for(char j = '0';j <= '9';j ++)        {            int k = i;            while(k && s[k] != j) k = nxt[k];            if(s[k] == j) k ++;            if(k != m) f.num[i][k] ++;        }    }    matrix fn = ksm(f,n),a(1,m);    a.num[0][0] = 1;    a = a * fn;    int ans = 0;    for(int i = 0;i < m;i ++)        ans = (ans + a.num[0][i]) % mod;    printf("%d\n",ans);    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.