您的位置:首页 > 其它

poj 3415 长度超过K的公共子串个数

2013-02-07 17:10 330 查看

1.将两个字符串连接起来中间用一个未出现字符隔开求后缀数组。

2.按K值将height数组分组,每组答案独立,分别统计

3.每一组求解时维护一个按height值单调递增的栈,使得统计时可平摊保证o(n)的复杂度。

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
usingnamespacestd;
constintnMax=210005;
longlongans=0;
intr[nMax],K,ha[nMax],top;
intsa[nMax],rank[nMax],height[nMax];
intwa[nMax],wb[nMax],wv[nMax],wd[nMax];
structST
{
inth;
longlongr,c;
}st[nMax];
intcmp(int*r,inta,intb,intl)
{
returnr[a]==r[b]&&r[a+l]==r[b+l];
}

voidda(int*r,intn,intm)
{
inti,j,p,*x=wa,*y=wb,*t;
for(i=0;i<m;i++)wd[i]=0;
for(i=0;i<n;i++)wd[x[i]=r[i]]++;
for(i=1;i<m;i++)wd[i]+=wd[i-1];
for(i=n-1;i>=0;i--)sa[--wd[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++)wd[i]=0;
for(i=0;i<n;i++)wd[wv[i]]++;
for(i=1;i<m;i++)wd[i]+=wd[i-1];
for(i=n-1;i>=0;i--)sa[--wd[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++;
}
}
}

voidcalHeight(int*r,intn){
inti,j,k=0;
for(i=1;i<=n;i++)rank[sa[i]]=i;//1->n
for(i=0;i<n;i++){
for(k?k--:0,j=sa[rank[i]-1];r[i+k]==r[j+k];k++);
height[rank[i]]=k;
}
}
voidslove(intb,intn)
{
for(inti=1;i<=n;i++)
{
if(height[i]<K)top=-1;
else
{
inth=height[i];
if(top!=-1&&h<=st[top].h)
{
longlongc=0;
while(st[top].h>=h&&top>-1)c+=st[top--].c;
st[++top].h=h;st[top].c=c;
st[top].r=(top==0?0:st[top-1].r)+st[top].c*(h-K+1);
}
if(ha[sa[i-1]]==b)
{
longlongt=(top==-1?0:st[top].r);
st[++top].h=h;st[top].c=1;
st[top].r=t+h-K+1;
}
if(ha[sa[i]]!=b)ans+=(top==-1?0:st[top].r);

}
}
}
intmain()
{
//freopen("test.txt","r",stdin);
chars[nMax];
while(scanf("%d",&K)&&K)
{
scanf("%s",s);
intn=strlen(s);
memset(ha,0,sizeof(ha));
ha
=2;s[n++]='z'+1;
scanf("%s",s+n);
for(inti=n;s[i];i++)ha[i]=1;
n=strlen(s);
for(inti=0;i<n;i++)
{
if(s[i]>='a')r[i]=s[i]-'a'+27;
elser[i]=s[i]-'A'+1;
}
r
=0;
da(r,n+1,57);
calHeight(r,n);

ans=0;
slove(0,n);slove(1,n);
printf("%lld\n",ans);
}
return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐