Suffix array + monotonic stack
Code
1#include <cstdio>2#include <algorithm>3#include <cstring>4 using namespacestd;5 Const intN =501000;6 7 Const intMAXN = N;8 9 structsuffixarray{Ten intWA[MAXN]; One intWB[MAXN]; A intWV[MAXN]; - intWS[MAXN]; - the intSA[MAXN]; - intRANK[MAXN]; - intHEIGHT[MAXN]; - intR[MAXN]; + intN - intM + A voidInputint*val,intLenintMax) { at for(inti =0; I < len;i++) -R[i] =Val[i]; -R[len] =0; -n =Len; -m =Max; - Calsa (); in calheight (); - } to + intcmpint*r,intAintBintl) { - return(R[a] = = R[b] && r[a + l] = = R[b +l]); the } * $ voidCalsa () {Panax Notoginseng intI, J, p, *x = WA, *y = WB, *T; - for(i =0; i < m;i++) Ws[i] =0; the for(i =0; i < n +1; i++) Ws[x[i] = r[i]]++; + for(i =1; i < m;i++) Ws[i] + = ws[i-1]; A for(i = N;i >=0; i--) Sa[--ws[x[i]] =i; the for(j =1, p =1;p < n +1; J *=2, M =p) { + for(P =0, I = N-j +1; i < n +1; i++) y[p++] =i; - for(i =0; i < n +1; i++)if(Sa[i] >= j) y[p++] = Sa[i]-J; $ for(i =0; i < n +1; i++) Wv[i] =X[y[i]]; $ for(i =0; i < m;i++) Ws[i] =0; - for(i =0; i < n +1; i++) ws[wv[i]]++; - for(i =1; i < m;i++) Ws[i] + = ws[i-1]; the for(i = N;i >=0; i--) Sa[--ws[wv[i]] =Y[i]; - for(t = x, x = y, y = t, p =1, x[sa[0]] =0, i =1; I < n +1; i++)WuyiX[sa[i]] = cmp (y, Sa[i-1], Sa[i], j)? P-1: p++; the } - } Wu - voidCalheight () { About intI, 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++); - } A + intLOG[MAXN]; the intbest[ -][MAXN]; - voidINITRMQ () { $log[0] = -1; the for(inti =1; I <= maxn;i++){ theLog[i]= (I & (i-1))? Log[i-1]: Log[i-1] +1 ; the } the for(inti =1; I <= N; i + +) best[0][i] =Height[i]; - for(inti =1; I <= Log[n]; i + +) { in intLimit = N-(1<<i) +1; the for(intj =1; J <= Limit; J + +) { theBEST[I][J] = (best[i-1][J] > best[i-1][j+ (1<<i>>1)]) ? best[i-1][j+ (1<<i>>1)]: best[i-1][j]; About } the } the } the intLcpintAintb) { +A = Rank[a]; b =Rank[b]; - if(A >b) { the intt =A;BayiA =b; theb =T; the } -A + +; - intt = log[b-a +1]; the return(Best[t][a] > Best[t][b-(1<<T) +1])? Best[t][b-(1<<T) +1]: best[t][a]; the } the }sa; the intA[n],i,len,top,stack[n]; - Long Longans,sum; the CharS[n]; the intMain () the {94scanf"%s",&s); thelen=strlen (s); the for(i=1; i<=len;i++) the {98Ans=ans+ (Long Long) i* (len-1); Abouta[i-1]=s[i-1]; - }101Sa.input (A,len, $);102 for(i=1; i<=len;i++)103 {104 while(sa.height[i]<Sa.height[stack[top]]) the {106sum=sum-(Long Long) (stack[top]-stack[top-1])*Sa.height[stack[top]];107top--;108 }109top++;stack[top]=i; thesum=sum+ (Long Long) (stack[top]-stack[top-1])*Sa.height[stack[top]];111ans=ans-2*sum; the }113printf"%lld\n", ans); the } the //3 1 4 2 5 0
[Ahoi2013] Differences