Time Limit: 5000MS Memory Limit: 65536K
Total Submissions: 9232 Accepted: 3066
Description
A substring of a string T is defined as:
T(i, k)=TiTi+1…Ti+k-1, 1≤i≤i+k-1≤|T|.
Given two strings A, B and one integer K, we define S, a set of triples (i, j, k):
S = {(i, j, k) | k≥K, A(i, k)=B(j, k)}.
You are to give the value of |S| for specific A, B and K.
Input
The input file contains several blocks of data. For each block, the first line contains one integer K, followed by two lines containing strings A and B, respectively. The input file is ended by K=0.
1 ≤ |A|, |B| ≤ 105
1 ≤ K ≤ min{|A|, |B|}
Characters of A and B are all Latin letters.
Output
For each case, output an integer |S|.
Sample Input
2
aababaa
abaabaa
1
xx
xx
0
Sample Output
22
5
Source
POJ Monthly–2007.10.06, wintokk
Sol
单调栈+后缀数组
论文题
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 200005
int t1[N],t2[N],c[N];
int sa[N],rk[N],ht[N];
int n,k,l1,l2;char s[N];
void DA(int m,int n){
int *x=t1,*y=t2;
for(int i=0;i<m;i++) c[i]=0;
for(int i=0;i<n;i++) c[x[i]=s[i]]++;
for(int i=1;i<m;i++) c[i]+=c[i-1];
for(int i=n-1;~i;i--) sa[--c[x[i]]]=i;
for(int k=1,p=0;k<=n;k<<=1,p=0){
for(int i=n-k;i<n;i++) y[p++]=i;
for(int i=0;i<n;i++) if(sa[i]>=k) y[p++]=sa[i]-k;
for(int i=0;i<m;i++) c[i]=0;
for(int i=0;i<n;i++) c[x[y[i]]]++;
for(int i=1;i<m;i++) c[i]+=c[i-1];
for(int i=n-1;~i;--i) sa[--c[x[y[i]]]]=y[i];
swap(x,y);m=1,x[sa[0]]=0;
for(int i=1;i<n;i++) x[sa[i]]=y[sa[i]]==y[sa[i-1]]&&
(y[sa[i]+k]==y[sa[i-1]+k])?m-1:m++;
if(m>=n) break;
}
}
void CalcHeight(int n){
for(int i=0;i<=n;i++) rk[sa[i]]=i;
for(int i=0,j,k=0;i<n;ht[rk[i++]]=k){
if(!rk[i]) continue;
j=sa[rk[i]-1];if(k) k--;
while(s[i+k]==s[j+k]) k++;
}
ht[0]=0;
}
int stk1[N],stk2[N],t;long long ans;
void GetAns(){
ans=0,t=0;long long tot=0,cnt;
for(int i=1;i<=n;i++){
if(ht[i]<k){tot=0,t=0;continue;}
if(cnt=0,sa[i-1]<l1) tot+=ht[i]-k+1,++cnt;
while(t&&ht[i]<=ht[stk1[t-1]])
t--,tot-=stk2[t]*(ht[stk1[t]]-ht[i]),cnt+=stk2[t];
stk1[t]=i,stk2[t++]=cnt;
if(sa[i]>l1) ans+=tot;
}
t=0,tot=0;
for(int i=1;i<=n;i++){
if(ht[i]<k){tot=0,t=0;continue;}
if(cnt=0,sa[i-1]>l1) tot+=ht[i]-k+1,++cnt;
while(t&&ht[i]<=ht[stk1[t-1]])
t--,tot-=stk2[t]*(ht[stk1[t]]-ht[i]),cnt+=stk2[t];
stk1[t]=i,stk2[t++]=cnt;
if(sa[i]<l1) ans+=tot;
}
}
char str1[N],str2[N];
int main(){
while(scanf("%d",&k),k){
scanf("%s%s",str1,str2);n=0;
for(int i=0;str1[i];i++) s[n++]=str1[i];
l1=n,s[n++]=1;
for(int i=0;str2[i];i++) s[n++]=str2[i];
s[n]=0;DA(128,n+1),CalcHeight(n);GetAns();printf("%lld\n",ans);
}
return 0;
}