样例1:
A=“xx”,B=“xx”,k=1,长度不小于k 的公共子串的个数是5。
样例2:
A =“aababaa”,B =“abaabaa”,k=2,长度不小于k 的公共子串的个数是22。
思路:
如果i后缀与j后缀的LCP长度为L, 在L不小于K的情况下, 它对答案的贡献为L - K + 1. 于是我们可以将两个串连起来, 中间加个奇葩的分隔符, 做一遍后缀数组, 并按height数组的值对后缀分组, 保证同组内的后缀间的LCP不小于K. 显然不同组间的答案是独立的, 我们可以单独处理每一组. 于是问题变成了: 在每一组内, 对每个A的后缀, 算出它之前B的后缀与之LCP的和(其实是LCP - K + 1, 后面都说成LCP), 再对每个B后缀, 算出它之前A的后缀与之LCP的和
统计的时候用一般暴力复杂度达到O(n^2),这里可以用单调栈优化:比如A1,A2,A3,Bx是四个后缀,他们rank连续,而且height单调递增,那么A1与A2的LCP可以就是A1与Bx的LCP,所以单调的时候就能边入栈边统计答案了,但是细节也是比较多的,比如入栈的是B的后缀和A的后缀还要分别处理,不单调的时候,出栈直到再次单调为止。
单调栈也是第一次遇到,其实就是维护一个栈里面的元素始终单调...http://blog.csdn.net/hopeztm/article/details/7868581这里有一个单调栈在一个经典DP中的运用
自己太弱了,这题用为什么能用单调栈优化O(n)解决自己一开始也不懂,看cxlove的代码看了两个半小时才彻底弄懂..
.http://blog.csdn.net/acm_cxlove/article/details/7946967
//6612K 860MS C++ 3114B
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int MAXN = 2e5+100;
int t1[MAXN],t2[MAXN],c[MAXN];
bool cmp(int *r,int a,int b,int l)
{
return r[a]==r[b]&&r[a+l]==r[b+l];
}
void da(int str[],int sa[],int rank[],int height[],int n,int m)
{
n++;
int i,j,p,*x=t1,*y=t2;
for(i=0;i<m;i++) c[i]=0;
for(i=0;i<n;i++) c[x[i]=str[i]]++;
for(i=1;i<m;i++) c[i]+=c[i-1];
for(i=n-1;i>=0;i--)sa[--c[x[i]]]=i;;
for(j=1;j<=n;j<<=1)
{
p=0;
for(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<m;i++) c[i]=0;
for(i=0;i<n;i++) c[x[y[i]]]++;
for(i=1;i<m;i++) c[i]+=c[i-1];;
for(i=n-1;i>=0;i--)sa[--c[x[y[i]]]]=y[i];
swap(x,y);
p=1;
x[sa[0]]=0;
for(i=1;i<n;i++) x[sa[i]]=cmp(y,sa[i-1],sa[i],j) ? p-1:p++;
if(p>=n)break;
m=p;
}
int k=0;
n--;
for(i=0;i<=n;i++) rank[sa[i]]=i;
for(i=0;i<n;i++)
{
if(k) k--;
j=sa[rank[i]-1];
while(str[i+k]==str[j+k]) k++;
height[rank[i]]=k;
}
}
int rank[MAXN],height[MAXN];
char s1[MAXN],s2[MAXN];
int r[MAXN];
int sa[MAXN];
int g;
struct node
{
int cnt;
int val;
};
node s[MAXN];
int main()
{
while(scanf("%d",&g),g)
{
scanf("%s%s",s1,s2);
int l1=strlen(s1),l2=strlen(s2);
int n=l1+l2+1;
for(int i=0;i<l1;i++)
r[i]=s1[i];
r[l1]='$';
for(int i=0;i<=l2;i++)
r[i+l1+1]=s2[i];
da(r,sa,rank,height,n,130);
ll ans=0;
ll top=0,cnt,tot=0;
//在每一组内, 对每个B的后缀, 算出它之前A的后缀与之LCP - K + 1的和
for(int i=1;i<=n;i++)
{
cnt=0;
if(height[i]<g)top=tot=0; //这组结束,下一组开始
else
{
if(sa[i-1]<l1) //如果前一个是A的前缀,那么有对答案贡献LCP-g+1
{
cnt++;
tot+=height[i]-g+1;
}
while(top!=0&&s[top-1].val>=height[i]) //不单调那么出栈直到单调
{
top--;
tot-=s[top].cnt*(s[top].val-height[i]);
cnt+=s[top].cnt;
}
s[top].cnt=cnt;
s[top++].val=height[i];
if(sa[i]>l1) ans+=tot; //当前是B的后缀就把前面累计的tot加在ans上
}
}
//在每一组内, 对每个A的后缀, 算出它之前B的后缀与之LCP - K + 1的和
tot=0,top=0;
for(int i=1;i<=n;i++)
{
cnt=0;
if(height[i]<g)
top=tot=0;
else
{
if(sa[i-1]>l1)
{
cnt++;
tot+=height[i]-g+1;
}
while(top!=0&&s[top-1].val>=height[i])
{
top--;
tot-=s[top].cnt*(s[top].val-height[i]) ;
cnt+=s[top].cnt;
}
s[top].val=height[i];
s[top++].cnt=cnt;
if(sa[i]<l1) ans+=tot;
}
}
printf("%I64d\n",ans);
}
return 0;
}