"Topic link" http://poj.org/problem?id=3415
"The main topic"
Find out the number of two common substrings with a string length greater than K.
Exercises
First, it's easy to think of the O (N2) algorithm, which connects a string with the B string plus the concatenation character,
Do a suffix array, match all suffixes of a and B respectively, Lcp-k+1 is the contribution to the answer,
But how to optimize it on this basis.
We can find that in the order of SA, the LCP of each suffix and the preceding string is the minimum value of the interval LCP,
Then we maintain a monotonic stack, merging all the monotonically decreasing LCP values,
Save the number and length, update the suffix of the previous a string to each suffix of the B string,
The contribution to the suffix of string A is updated to the suffix of string B.
Code
#include <cstdio> #include <cstring> #include <algorithm> using namespace std;typedef long long ll; const int N=400010;int N,rank[n],sa[n],h[n],tmp[n],cnt[n];char s[n];void suffixarray (int n,int m) {int i,j,k;n++; for (i=0;i<2*n+5;i++) rank[i]=sa[i]=h[i]=tmp[i]=0; for (i=0;i<m;i++) cnt[i]=0; for (i=0;i<n;i++) cnt[rank[i]=s[i]]++; for (i=1;i<m;i++) cnt[i]+=cnt[i-1]; for (i=0;i<n;i++) sa[--cnt[rank[i]]]=i; for (K=1;k<=n;k<<=1) {for (i=0;i<n;i++) {j=sa[i]-k; if (j<0) j+=n; Tmp[cnt[rank[j]]++]=j; }sa[tmp[cnt[0]=0]]=j=0; for (i=1;i<n;i++) {if (rank[tmp[i]]!=rank[tmp[i-1]]| | RANK[TMP[I]+K]!=RANK[TMP[I-1]+K]) cnt[++j]=i; Sa[tmp[i]]=j; }memcpy (rank,sa,n*sizeof (int)); memcpy (sa,tmp,n*sizeof (int)); if (j>=n-1) break; }for (j=rank[h[i=k=0]=0];i<n-1;i++,k++) while (~k&&s[i]!=s[sa[j-1]+k]) h[j]=k--, j=rank[sa[j]+1];} int Na[n],nb[n],k,st[n], Top;int Main () {while (~SCANF ("%d", &k), K) {scanf ("%s", s); int Len=strlen (s); s[len]= ' # '; scanf ("%s", s+len+1); N=strlen (s); Suffixarray (n,128); for (int i=2;i<=n;i++) H[i]=max (0,h[i]-k+1); ll Ans=0,w1=0,w2=0; Top=0; for (int i=2;i<=n;i++) {st[++top]=h[i]; if (Sa[i-1]<len) na[top]=1,nb[top]=0,w1+=h[i]; else Na[top]=0,nb[top]=1,w2+=h[i]; while ((top>1) &&st[top]<=st[top-1]) {w1-=na[top-1]* (st[top-1]-st[top]); w2-=nb[top-1]* (St[top-1]-st[top]); Na[top-1]+=na[top]; Nb[top-1]+=nb[top]; st[top-1]=st[top--]; }if (Sa[i]<len) ans+=w2; else ANS+=W1; }printf ("%lld\n", ans); }return 0;}
POJ 3415 Common substrings (suffix array + monotonic stack)