(http://acm.hust.edu.cn/vjudge/contest/view.action?cid=105595#problem/J)
题意:字符串A,B,问A,B有多少相同子串。
解法:后缀数组+线段树,+优先队列也行。我写的是+优先队列的版本。也能用后缀自动机做,应该还方便一点。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <queue>
//#include <tr1/unordered_set>
//#include <tr1/unordered_map>
#include <bitset>
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
#define inf 1e9
#define debug(a) cout << #a" = " << (a) << endl;
#define debugarry(a, n) for (int i = 0; i < (n); i++) { cout << #a"[" << i << "] = " << (a)[i] << endl; }
#define clr(x, y) memset(x, y, sizeof x)
#define ll long long
#define ull unsigned long long
#define FOR(i,a,b) \
for(i=a;a<b?i<=b:i>=b;a<b?i++:i--)
const int maxn = 100000*2*2+100;
struct suffix_array{
char s[maxn];
int sa[maxn],t[maxn],t2[maxn],c[maxn];
int n;
void build_sa(int m)
{
int i,*x=t,*y=t2;
FOR(i,0,m-1) c[i]=0;
FOR(i,0,n-1) c[x[i]=s[i]]++;
FOR(i,1,m-1) c[i]+=c[i-1];
FOR(i,n-1,0) sa[--c[x[i]]]=i;
for(int k=1;k<=n;k<<=1){
int p=0;
FOR(i,n-k,n-1) y[p++]=i;
FOR(i,0,n-1) if(sa[i]>=k) y[p++]=sa[i]-k;
FOR(i,0,m-1) c[i]=0;
FOR(i,0,n-1) c[x[y[i]]]++;
FOR(i,0,m-1) c[i]+=c[i-1];
FOR(i,n-1,0) sa[--c[x[y[i]]]]=y[i];
swap(x,y);
p=1;
x[sa[0]]=0;
FOR(i,1,n-1)
x[sa[i]]=y[sa[i-1]]==y[sa[i]]&&
y[sa[i-1]+k]==y[sa[i]+k]?p-1:p++;
if(p>=n) break;
m=p;
}
}
int Rank[maxn],height[maxn];
void getHeight()
{
int k=0;
for(int i=0;i<n;i++) Rank[sa[i]]=i;
for(int i=0;i<n;i++){
if(k)k--;
int j=sa[Rank[i]-1];
while(s[i+k]==s[j+k]) k++;
height[Rank[i]]=k;
}
}
}su;
char s[maxn],s2[maxn];
int len,K;
int top,h[maxn];
ll sum[maxn],cnt[maxn];
int main()
{
//freopen("input.txt","r",stdin);
while(~scanf("%d",&K))
{
if(!K) break;
scanf("%s%s",s,s2);
len=strlen(s);
strcat(s,"$");
strcat(s,s2);
strcpy(su.s,s);
su.n=strlen(su.s)+1;
su.build_sa(255);
su.getHeight();
ll ans = 0 , cursum;
top=0;
cursum=0;
for(int i=1;i<su.n;i++)
{
int th = su.height[i];
if( th < K )
{
top=0;
cursum=0;
}else{
ll tcnt=0,tsum=0;
while( top && h[top-1] >= th )
{
top--;
tcnt += cnt[top];
tsum += sum[top] - cnt[top]*(h[top]-th);
cursum -= cnt[top]*(h[top]-th);
}
if( tcnt )
{
h[top] = th;
cnt[top] = tcnt;
sum[top] = tsum;
top++;
}
}
if( su.sa[i] <= len )
ans += cursum;
else
{
h[top]=su.n;
cnt[top]=1;
sum[top]=su.n-K+1;
cursum+=su.n-K+1;
top++;
}
}
top=0;
cursum=0;
for(int i=1;i<su.n;i++)
{
int th = su.height[i];
if( th < K )
{
top=0;
cursum=0;
}else{
ll tcnt=0,tsum=0;
while( top && h[top-1] >= th )
{
top--;
tcnt += cnt[top];
tsum += sum[top] - cnt[top]*(h[top]-th);
cursum -= cnt[top]*(h[top]-th);
}
if( tcnt )
{
h[top] = th;
cnt[top] = tcnt;
sum[top] = tsum;
top++;
}
}
if( su.sa[i] > len )
ans += cursum;
else
{
h[top]=su.n;
cnt[top]=1;
sum[top]=su.n-K+1;
cursum+=su.n-K+1;
top++;
}
}
printf("%I64d\n",ans);
}
return 0;
}