POJ 1625 Censored!

来源:互联网 发布:java画图api 编辑:程序博客网 时间:2024/05/01 03:37

Description
The alphabet of Freeland consists of exactly N letters. Each sentence of Freeland language (also known as Freish) consists of exactly M letters without word breaks. So, there exist exactly N^M different Freish sentences.
But after recent election of Mr. Grass Jr. as Freeland president some words offending him were declared unprintable and all sentences containing at least one of them were forbidden. The sentence S contains a word W if W is a substring of S i.e. exists such k >= 1 that S[k] = W[1], S[k+1] = W[2], …,S[k+len(W)-1] = W[len(W)], where k+len(W)-1 <= M and len(W) denotes length of W. Everyone who uses a forbidden sentence is to be put to jail for 10 years.
Find out how many different sentences can be used now by freelanders without risk to be put to jail for using it.


【题目分析】
多模板的题目,显然应该用AC自动机,然后计数类的dp。如果trie[ j ][ k ] 不是一个单词的末尾,就可以累加到dp[ i+1 ] [ trie[ j ][ k ] ]上。
最后统计输出。由于压位储存。注意前导零的输出。


【代码】

#include <cstdio>#include <map>#include <cstring>#include <queue>using namespace std;int n,m,q,tot=1;map<char,int>mp;char s[60];int tr[210][75],fail[210],v[210];struct num{    int l,a[100];    num operator + (const num &x) const    {        num ans;        int len;        memset(ans.a,0,sizeof(ans.a));        for (int i=1;i<=l||i<=x.l;i++)        {            ans.a[i]+=a[i]+x.a[i];            ans.a[i+1]+=ans.a[i]/10000;            ans.a[i]%=10000;        }        if (l<x.l) len=x.l+1;        else len=l+1;        while (!ans.a[len]&&len) len--;        ans.l=len;        return ans;    }}dp[110][110],ans;void insert(){    scanf("%s",s);    int now=1,len=strlen(s)-1;    for (int i=0;i<=len;++i)    {        if (!tr[now][mp[s[i]]]) tr[now][mp[s[i]]]=++tot;        now=tr[now][mp[s[i]]];    }    v[now]=true;}void bfs(){    queue <int> q;    q.push(1);    while (!q.empty())    {        int x=q.front();q.pop();v[x]|=v[fail[x]];        for (int i=0;i<n;++i)        {            int j=fail[x];            while (j&&!tr[j][i]) j=fail[j];            if (tr[x][i]) fail[tr[x][i]]=j?tr[j][i]:1,q.push(tr[x][i]);            else  tr[x][i]=j?tr[j][i]:1;        }    }}void dpp(){    dp[0][1].a[1]=1; dp[0][1].l=1;    for (int i=0;i<m;++i)    {        for (int j=1;j<=tot;++j)        {            for (int k=0;k<n;++k)            {                int p=tr[j][k];                if (v[p]) continue;                dp[i+1][p]=dp[i+1][p]+dp[i][j];            }        }    }}void prt(num x){    printf("%d",x.a[x.l]);    for (int i=x.l-1;i>=1;i--)    {        int y=x.a[i];        if (y<1000) printf("0");        if (y<100) printf("0");        if (y<10) printf("0");        printf("%d",y);    }}int main(){    scanf("%d%d%d",&n,&m,&q); scanf("%s",s);    for (int i=0;i<n;++i) mp[s[i]]=i;    for (int i=0;i<q;++i) insert();    bfs(),dpp();    for (int i=1;i<=tot;++i)        if (!v[i]) ans=ans+dp[m][i];    prt(ans);    printf("\n");}
0 0
原创粉丝点击