HDU 4416

来源:互联网 发布:godaddy域名转走 编辑:程序博客网 时间:2024/06/16 06:15

http://acm.hdu.edu.cn/showproblem.php?pid=4416

#include <stdio.h>#include <iostream>#include <string.h>#include <algorithm>#define maxn 400202#define MME(i,j) memset(i,j,sizeof(i))#include <string>using namespace std;int wa[maxn],wb[maxn],wv[maxn],Ws[maxn];int cmp(int *r,int a,int b,int l){return r[a]==r[b]&&r[a+l]==r[b+l];}void da(const int *r,int *sa,int n,int 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(j=1,p=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,p=1,x[sa[0]]=0,i=1;i<n;i++)            x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;    }    return;}int sa[maxn],Rank[maxn],height[maxn];//求height数组void calheight(const int *r,int *sa,int 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++);    return;}int a[maxn],pos[maxn];char str[maxn];int main(){    int t,cas;    scanf("%d",&t);    while(t--)    {        scanf("%d",&cas);        scanf("%s",str);        int len=strlen(str),num=30,m=0;  // len 为 字符串 A 长度        for(int i=0;str[i];i++)            a[m++]=str[i]-'a'+1;        for(int i=0;i<cas;i++)        {            a[m++]=num++;            scanf("%s",str);            for(int k=0;str[k];k++)                a[m++]=str[k]-'a'+1;        }        a[m]=0;        da(a,sa,m+1,num+1);        calheight(a,sa,m);        MME(pos,0);        int tmp=maxn;        for(int i=1;i<=m;i++){            if(sa[i]<len){                if(height[i]<tmp) tmp = height[i];                if(pos[sa[i]] <tmp) pos[sa[i]] = tmp;            }            else tmp =maxn;        }        tmp = maxn;        for(int i=m;i>=1;i--){            if(sa[i-1]<len){            if(height[i]<tmp)                tmp=height[i];            if(pos[sa[i-1]] <tmp) pos[sa[i-1]]=tmp;            }else tmp = maxn;        }        for(int i=1;i<=m;i++){            if(sa[i]<len&&sa[i-1]<len){                if(pos[sa[i-1]]<height[i])                    pos[ sa[i-1] ] = height[i];            }        }        long long int ans = (long long)len*(len+1)/2;        for(int i=0;i<len;i++)            ans-=pos[i];        static int times=1;          printf("Case %d: %I64d\n",times++,ans);    }    return 0;}
0 0
原创粉丝点击