POJ3415
题意为给定两个字符串A和B,求长度不小于k的公共子串的个数(可以相同)
这道题我们先考虑暴力的做法,我们可以将两串拼接求出 height h e i g h t 数组,答案为所有分别属于A,B的后缀的 (lcp−k+1) ( l c p − k + 1 ) 之和,我们可以 n2 n 2 解决这个问题。
但是本题的范围 n2 n 2 是会超时的,所以我们要考虑 height h e i g h t 数组的性质, lcp(i,j) l c p ( i , j ) 就是 height[i]−−−−−height[j] h e i g h t [ i ] − − − − − h e i g h t [ j ] 中的最小值,所以我们可以构造一个单调递增的单调栈,用来维护到某个位置之前的 height h e i g h t 的递增情况,如果当前 height[i]<sta[top] h e i g h t [ i ] < s t a [ t o p ] ,那么表示当前栈顶元素不能表示接下来的 lcp l c p ,我们需要将栈顶的贡献修改,然后更换栈顶元素,在维护栈顶元素下标的同时,还要维护这个栈顶元素代表着前面多少个后缀的最小 height h e i g h t ,以便于最后算贡献。
算贡献的时候,要减去原来的贡献,也就是之前栈顶元素的贡献 ∗ ∗ 该栈顶元素代替的相同数量,然后加上当前的贡献 ∗ ∗ 当前栈顶元素代替的相同数量,然后修改当前栈顶元素以及所代表的数量,然后 ans a n s 统计贡献
以A入栈B统计和B入栈A统计的顺序分别两次计算,最终得到的即为正确答案。
POJ3415代码
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define maxn 300005
int wa[maxn],wb[maxn],wsf[maxn],wv[maxn],sa[maxn];
int rank[maxn],height[maxn],s[maxn];
char str1[maxn],str2[maxn];
int sta[maxn];
int cnt[maxn];
int cmp(int *r,int a,int b,int k)
{
return r[a]==r[b]&&r[a+k]==r[b+k];
}
void getsa(int *r,int *sa,int n,int m)
{
int i,j,p,*x=wa,*y=wb,*t;
for(i=0; i<m; i++) wsf[i]=0;
for(i=0; i<=n; i++) wsf[x[i]=r[i]]++;
for(i=1; i<m; i++) wsf[i]+=wsf[i-1];
for(i=n; i>=0; i--) sa[--wsf[x[i]]]=i;
p=1;
j=1;
for(; p<=n; j*=2,m=p)
{
for(p=0,i=n+1-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++) wsf[i]=0;
for(i=0; i<=n; i++) wsf[wv[i]]++;
for(i=1; i<m; i++) wsf[i]+=wsf[i-1];
for(i=n; i>=0; i--) sa[--wsf[wv[i]]]=y[i];
t=x;
x=y;
y=t;
x[sa[0]]=0;
for(p=1,i=1; i<=n; i++)
x[sa[i]]=cmp(y,sa[i-1],sa[i],j)? p-1:p++;
}
}
void getheight(int *r,int n)
{
int i,j,k=0;
for(i=1; i<=n; i++) rank[sa[i]]=i;
for(i=0; i<n; i++)
{
if(k)
k--;
else
k=0;
j=sa[rank[i]-1];
while(r[i+k]==r[j+k])
k++;
height[rank[i]]=k;
}
}
int main()
{
int len,n,k;
while(~scanf("%d",&k)!=EOF)
{
if(k==0) break;
scanf("%s%s",str1,str2);
n=0;
len=strlen(str1);
for(int i=0;i<len;i++)
s[n++]=str1[i]-'A'+1;
s[n++]=60;
len=strlen(str2);
for(int i=0;i<len;i++)
s[n++]=str2[i]-'A'+1;
s[n]=0;
getsa(s,sa,n,100);
getheight(s,n);
len=strlen(str1);
long long ans=0;
int top=0;
long long sum=0;
for(int i=2;i<=n-1;i++)
{
if(height[i]<k)
{
top=0;
sum=0;
}
else
{
int num=0;
while(top&&height[i]<sta[top])
{
sum-=1LL*(sta[top]-k+1)*cnt[top];
sum+=1LL*(height[i]-k+1)*cnt[top];
num+=cnt[top];
top--;
}
sta[++top]=height[i];
if(sa[i-1]>len)
{
sum+=(long long)height[i]-k+1;
cnt[top]=num+1;
}
else cnt[top]=num;
if(sa[i]<len) ans+=sum;
}
}
top=0;
sum=0;
for(int i=2;i<=n-1;i++)
{
if(height[i]<k)
{
top=0;
sum=0;
}
else
{
int num=0;
while(top&&height[i]<sta[top])
{
sum-=1LL*(sta[top]-k+1)*cnt[top];
sum+=1LL*(height[i]-k+1)*cnt[top];
num+=cnt[top];
top--;
}
sta[++top]=height[i];
if(sa[i-1]<len)
{
sum+=(long long)height[i]-k+1;
cnt[top]=num+1;
}
else cnt[top]=num;
if(sa[i]>len) ans+=sum;
}
}
printf("%lld\n",ans);
}
return 0;
}