这道题做的好艰难呀,起初是TLE,发现O(n^2)确实不行。n最大可能是100000,铁定TLE。然后想着怎么来优化,想了好久也没有思路
后来借鉴了打个大神的思路的处理技巧:http://blog.csdn.net/acm_cxlove/article/details/7946967
我说一下自己的理解吧:
可以发现两个后缀的最长公共前缀为这一段的height值的最小值。
这是关键,所以维护一个 严格单调递增的 栈,在处理过程中,我们需要记录一个当前合法的串A的后缀贡献的子串数量,当加入进来一个B串时候,所有比其小的串A后缀都应该被纳入计算,比其大的部分我们应该减掉, 此时就需要记录那部分的数量。 中间过程不太好用文字描述。。。具体看代码吧:
#include<iostream>
#include<string.h>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define MAXD 201000
#define MAXL 300
using namespace std;
char r[MAXD];
int Rank[MAXD], height[MAXD];
int sa[MAXD], wa[MAXD], wb[MAXD], WS[MAXL], wv[MAXD]; //WS 的大小是最大字符的大小。其他的是串长大小
//r数组存放字符的值
int cmp(int *p, int x, int y, int l)
{
return p[x] == p[y] && p[x + l] == p[y + l];
}
void da(int n, int m) //n为字符串长度,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(p = 1, j = 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, x[sa[0]] = 0, p = 1, i = 1; i < n; i ++)
x[sa[i]] = cmp(y, sa[i - 1], sa[i], j) ? p - 1: p ++;
}
}
void calheight(int n) //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 ++);
}
/*****************以上都是后缀数组模板,下面的是具体问题的处理。******************/
char b[MAXD];
int K;
int len1,len;
struct Node
{
int h,cnt; //对应的height值以及 超出部分的数量。
};
Node st[MAXD];
long long work1()
{
int i,j;
long long ans=0;
long long top=0,tot=0;
for(i=1;i<=len;i++)
{
if(height[i]<K)
{
top=0;tot=0;
}
else
{
int cnt=0;
if(sa[i-1]<len1) cnt++,tot+=height[i]-K+1;
while(top>0&&height[i]<=st[top-1].h)
{
top--;
tot-=st[top].cnt*(st[top].h-height[i]);
cnt+=st[top].cnt;
}
st[top].h=height[i];st[top++].cnt=cnt;
if(sa[i]>len1) ans+=tot;
}
}
return ans;
}
long long work2()
{
int i,j;
long long ans=0;
long long top=0,tot=0;
for(i=1;i<=len;i++)
{
if(height[i]<K)
{
top=0;tot=0;
}
else
{
int cnt=0;
if(sa[i-1]>len1) cnt++,tot+=height[i]-K+1;
while(top>0&&height[i]<=st[top-1].h)
{
top--;
tot-=st[top].cnt*(st[top].h-height[i]);
cnt+=st[top].cnt;
}
st[top].h=height[i],st[top++].cnt=cnt;
if(sa[i]<len1) ans+=tot;
}
}
return ans;
}
int main()
{
int i,j;
int n;
while(scanf("%d",&K),K)
{
getchar();
gets(r);
gets(b);
len1=strlen(r);
r[len1]='$';
r[len1+1]=0;
strcat(r,b);
len=strlen(r);
memset(Rank,0,sizeof(Rank));
memset(height,0,sizeof(height));
da(len+1,300);
calheight(len);
long long ans=0;
ans+=work1();
ans+=work2();
printf("%lld\n",ans);
}
return 0;
}