hdu 4029 后缀数组

来源:互联网 发布:ubuntu离线安装包下载 编辑:程序博客网 时间:2024/04/29 02:40

这道题刚开始就知道是后缀数组,可是一直没有突破口。

后来看了大牛的博客才知道要hash。

参考:http://blog.csdn.net/acm_cxlove/article/details/7980456

代码如下:

//r数组存放字符的值#include<iostream>#include<cstring>#include<cstdio>#include<cstring>#include<map>#include<algorithm>#define MAXD 1<<16using namespace std;int r[MAXD], Rank[MAXD], height[MAXD];int sa[MAXD], wa[MAXD], wb[MAXD], WS[MAXD], wv[MAXD];int cmp(int *p, int x, int y, int l){    return p[x] == p[y] && p[x + l] == p[y + l];}void da(int n, int m)      //n为字符串长度+1,m为字符的最大值{    int i, j, p, *x = wa, *y = wb, *t;    for(i = 0; i < m; i ++)        WS[i] = 0;    for(i = 0; i < n; i ++)        ++ WS[x[i] = r[i]];    for(i = 1; i < m; i ++)        WS[i] += WS[i - 1];    for(i = n - 1; i >= 0; i --)        sa[-- WS[x[i]]] = i;    for(p = 1, j = 1; p < n; j *= 2, m = p)    {        for(p = 0, i = n - j; i < n; i ++)            y[p ++] = i;        for(i = 0; i < n; i ++)            if(sa[i] >= j)                y[p ++] = sa[i] - j;        for(i = 0; i < n; i ++)            wv[i] = x[y[i]];        for(i = 0; i < m; i ++)            WS[i] = 0;        for(i = 0; i < n; i ++)            ++ WS[wv[i]];        for(i = 1; i < m; i ++)            WS[i] += WS[i - 1];        for(i = n - 1; i >= 0; i --)            sa[-- WS[wv[i]]] = y[i];        for(t = x, x = y, y = t, x[sa[0]] = 0, p = 1, i = 1; i < n; i ++)            x[sa[i]] = cmp(y, sa[i - 1], sa[i], j) ? p - 1: p ++;    }}void calheight(int n)  //n为串的长度{    int i, j, k = 0;    for(i = 1; i <= n; i ++)        Rank[sa[i]] = i;    for(i = 0; i < n; height[Rank[i ++]] = k)        for(k ? -- k : 0, j = sa[Rank[i] - 1]; r[i + k] == r[j + k]; k ++);}int N,M,casei,w;char ch[133][133];__int64 h[133][133],ans,tot;map<__int64,int> mymap;int Hash=31,cnt;int T;int main(){    int i,j;    scanf("%d",&T);    while(T--)    {        casei++;        memset(h,0,sizeof(h));        scanf("%d%d",&N,&M);        ans=(((N+1)*N)/2)*(((M+1)*M)/2);        getchar();        for(i=0;i<N;i++)        {            scanf("%s",ch[i]);        }        for(w=1;w<=M;w++)        {            tot=1;            cnt=0;            mymap.clear();            for(i=0;i<N;i++)            {                for(j=0;j+w-1<M;j++)                {                    h[i][j]=h[i][j]*Hash+ch[i][j+w-1]-'A';                    if(mymap.find(h[i][j])==mymap.end())                    {                        mymap[h[i][j]]=tot++;                    }                }            }            for(j=0;j+w-1<M;j++)            {                for(i=0;i<N;i++)                {                    r[cnt++]=mymap[h[i][j]];                }                r[cnt++]=tot++;            }            r[cnt]=0;            da(cnt+1,tot);            calheight(cnt);            for(i=0;i<=cnt;i++) ans-=height[i];        }        printf("Case #%d: %I64d\n",casei,ans);    }}

 

0 0