求两个字符串的长度大于等于k的公共子串的个数。
思路:首先我们可以发现实际上这个问题就是求解这个:(画个后缀数组出来就明白)
Σ
Σ
l
c
p
(
i
,
j
)
−
k
+
1
ΣΣlcp(i,j)-k+1
ΣΣlcp(i,j)−k+1
然后暴力求解的话就是枚举两个字符串的后缀,但这样复杂度会到n^2,所以考虑优化。这里可以用单调栈来维护,跑两边,一遍是s1入栈,s2来统计,一遍s2入栈,s1统计,两个答案一加就是总答案。
具体思路可以看这个视频(类似的题目都是要求height数组的任意区间min):这里
AC代码:
#include <cstdio>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
using namespace std;
typedef long long LL;
const int maxn=2e5+10;
char s[maxn];
char str[maxn];
int y[maxn],x[maxn],cnt[maxn],sa[maxn],rk[maxn],height[maxn];
int n,m;
int tag;
int k;
void get_SA()
{
memset(cnt,0,sizeof(cnt));
m=300;
for (int i=1;i<=n;++i) ++cnt[x[i]=s[i]];
//x[i]是第i个元素的第一关键字
for (int i=2;i<=m;++i) cnt[i]+=cnt[i-1];
for (int i=n;i>=1;--i) sa[cnt[x[i]]--]=i;
for (int k=1;k<=n;k<<=1)
{
int num=0;
for (int i=n-k+1;i<=n;++i) y[++num]=i;
//y[i]表示第二关键字排名为i的数,第一关键字的位置
for (int i=1;i<=n;++i) if (sa[i]>k) y[++num]=sa[i]-k;
for (int i=1;i<=m;++i) cnt[i]=0;
for (int i=1;i<=n;++i) ++cnt[x[i]];
for (int i=2;i<=m;++i) cnt[i]+=cnt[i-1];//第一关键字排名为1~i的数有多少个
for (int i=n;i>=1;--i) sa[cnt[x[y[i]]]--]=y[i],y[i]=0;
swap(x,y);
x[sa[1]]=1;num=1;
for (int i=2;i<=n;++i)
x[sa[i]]=(y[sa[i]]==y[sa[i-1]] && y[sa[i]+k]==y[sa[i-1]+k]) ? num : ++num;
if (num==n) break;
m=num;
}
}
void get_height()
{
int k=0;
for (int i=1;i<=n;++i) rk[sa[i]]=i;
for (int i=1;i<=n;++i)
{
if (rk[i]==1) continue;//第一名height为0
if (k) --k;//h[i]>=h[i-1]+1;
int j=sa[rk[i]-1];
while (j+k<=n && i+k<=n && s[i+k]==s[j+k]) ++k;
height[rk[i]]=k;//h[i]=height[rk[i]];
}
}
struct node{
LL h;
int wide;
};
LL solve()
{
LL ans=0;
stack<node> stk;
LL tot=0,w=0;
for(int i=2;i<=n;i++){
if(height[i]<k){
while(!stk.empty()) stk.pop();
tot=w=0;
continue;
}
w=0;
if(sa[i-1]<tag){
w++;
tot+=(LL)(height[i]-k+1);
}
while(!stk.empty()&&stk.top().h>height[i]){
tot-=(LL)stk.top().wide*(stk.top().h-(LL)height[i]);
w+=(LL)stk.top().wide;
stk.pop();
}
stk.push({height[i],w});
if(sa[i]>tag) ans+=tot;
}
while(!stk.empty()) stk.pop();
tot=0,w=0;
for(int i=2;i<=n;i++){
if(height[i]<k){
while(!stk.empty()) stk.pop();
tot=w=0;
continue;
}
w=0;
if(sa[i-1]>tag){
w++;
tot+=(LL)(height[i]-k+1);
}
while(!stk.empty()&&stk.top().h>height[i]){
tot-=(LL)stk.top().wide*(stk.top().h-(LL)height[i]);
w+=(LL)stk.top().wide;
stk.pop();
}
stk.push({height[i],w});
if(sa[i]<tag) ans+=tot;
}
return ans;
}
int main()
{
while(scanf("%d",&k)!=EOF){
if(!k) break;
scanf("%s",str+1);
n=strlen(str+1);
for(int i=1;i<=n;i++) s[i]=str[i];
s[++n]='#';
tag=n;
scanf("%s",str+1);
int tmp=strlen(str+1);
for(int i=1;i<=tmp;i++) s[i+n]=str[i];
n+=tmp;
get_SA();
get_height();
LL ans=solve();
printf("%lld\n",ans);
}
}