ZOJ3891 K-hash 后缀自动机SAM

来源:互联网 发布:一淘网首页淘宝网 编辑:程序博客网 时间:2024/06/05 09:09

题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5561

题意:给出一个整数K(<=32)和一个长度50000以内由十进制数构成的字符串S,要求统计S的不重复子串所表示的数对K取模的结果。


本题属于SAM入门题,当时在做zoj月赛时还没学,学完后发现很简单。果然SAM功能很强大。

题解:建造后缀自动机,按拓扑序从小到大进行dp,记录到此节点取模得到d的方案数。

具体一点,y->num[(i*10+j)] += x->num[i] if trans(x,j)

特别注意0的情况,开头不能有0,最优统计0的个数时,看root->go[0]是否存在。

最后从0到tot节点的方案数累加即可。


代码:

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn = 50000*2+10;long long ans[34];int k;struct State{    State *pre , *go[11] , *nxt;    int val,cnt;    long long num[34];    State():        pre(0) , val(0){        memset(go,0,sizeof(go));        memset(num,0,sizeof(num));    }    void init(){        memset(go,0,sizeof(go));        memset(num,0,sizeof(num));        pre = nxt = NULL;        val = cnt = 0;    }} *root , *last , *cur;State statePool[maxn*2] , *first[maxn]={};int tot = 0;void init(int L){    for(int i=0;i<=L;i++) first[i]=0;    for(int i=0;i<=L*2+5;i++) statePool[i].init();    cur = statePool;    root = last = cur++;}void extend(int w){    State *p = last , *np = cur++;    np->val = p->val + 1;    np->cnt = 1;    while(p && !p->go[w])        p->go[w] = np , p = p->pre;    if(!p)        np->pre = root;    else{        State *q = p->go[w];        if(p->val+1==q->val){            np->pre = q;        }else{            State *nq = cur++;            memcpy(nq->go,q->go,sizeof q->go);            nq->val = p->val + 1;            nq->pre = q->pre;            q->pre = nq;            np->pre = nq;            while(p && p->go[w]==q)                p->go[w] = nq , p = p->pre;        }    }    last = np;}void start(char *s){    int L = strlen(s);    init(L);    for(int i=0;i<L;i++)        extend(s[i]-'0');    for(State *i = statePool;i!=cur;i++)        i->nxt = first[i->val] , first[i->val] = i;    for(int i=1;i<=9;i++)if(root->go[i]){        root->go[i]->num[i%k] = 1;    }    tot = 1;    for(int it=1;it<=L;it++){        for(State *i=first[it];i;i=i->nxt){            tot++;            for(int j=0;j<=9;j++)if(i->go[j]){                for(int d=0;d<k;d++){                    int he = (d*10+j)%k;                    i->go[j]->num[he] += i->num[d];                }            }        }    }    for(int i=0;i<tot;i++)        for(int j=0;j<k;j++)            ans[j] += statePool[i].num[j];    if(root->go[0])        ans[0] += 1;}char s[maxn];int main(){    while(scanf("%s",s)!=EOF){        scanf("%d",&k);        memset(ans,0,sizeof(ans));        start(s);        for(int i=0;i<=k-1;i++){            cout<<ans[i];            if(i==k-1) puts("");            else printf(" ");        }    }    return 0;}


0 0
原创粉丝点击