bzoj3238 [Ahoi2013]差异
树状数组+单调栈
计算出每个后缀的前面、后面第一个h[]比它小的(前闭后开),乘起来计算答案
1 #include<algorithm> 2 #include<iostream> 3 #include<cstdlib> 4 #include<cstring> 5 #include<cstdio> 6 #include<string> 7 #include<cmath> 8 #include<ctime> 9 #include<queue> 10 #include<stack> 11 #include<map> 12 #include<set> 13 #define rre(i,r,l) for(int i=(r);i>=(l);i--) 14 #define re(i,l,r) for(int i=(l);i<=(r);i++) 15 #define Clear(a,b) memset(a,b,sizeof(a)) 16 #define inout(x) printf("%d",(x)) 17 #define douin(x) scanf("%lf",&x) 18 #define strin(x) scanf("%s",(x)) 19 #define LLin(x) scanf("%lld",&x) 20 #define op operator 21 #define CSC main 22 typedef unsigned long long ULL; 23 typedef const int cint; 24 typedef long long LL; 25 using namespace std; 26 void inin(int &ret) 27 { 28 ret=0;int f=0;char ch=getchar(); 29 while(ch<'0'||ch>'9'){if(ch=='-')f=1;ch=getchar();} 30 while(ch>='0'&&ch<='9')ret*=10,ret+=ch-'0',ch=getchar(); 31 ret=f?-ret:ret; 32 } 33 char s[500050]; 34 int n,sa[500050],c[500050],t[500050],t2[500050],h[500050]; 35 void build_sa(int m) 36 { 37 int *x=t,*y=t2; 38 re(i,0,n-1)x[i]=s[i],c[x[i]]++; 39 re(i,1,m)c[i]+=c[i-1]; 40 rre(i,n-1,0)sa[--c[x[i]]]=i; 41 for(int k=1;k<=n;k<<=1) 42 { 43 int p=0; 44 rre(i,n-1,n-k)y[p++]=i; 45 re(i,0,n-1)if(sa[i]>=k)y[p++]=sa[i]-k; 46 re(i,0,m-1)c[i]=0; 47 re(i,0,n-1)c[x[y[i]]]++; 48 re(i,1,m-1)c[i]+=c[i-1]; 49 rre(i,n-1,0)sa[--c[x[y[i]]]]=y[i]; 50 swap(x,y); 51 x[sa[0]]=0,p=1; 52 re(i,0,n-1)x[sa[i]]=y[sa[i]]==y[sa[i-1]]&&y[sa[i]+k]==y[sa[i-1]+k]?p-1:p++; 53 if(p>=n)return ; 54 m=p; 55 } 56 } 57 int rank[500050]; 58 void build_height() 59 { 60 int k=0; 61 re(i,0,n-1)rank[sa[i]]=i; 62 re(i,0,n-1) 63 { 64 if(k)k--; 65 if(!rank[i])continue; 66 int j=sa[rank[i]-1]; 67 while(s[i+k]==s[j+k])k++; 68 h[rank[i]]=k; 69 } 70 } 71 int l[500050],r[500050],sta[500050]; 72 LL ans; 73 int main() 74 { 75 strin(s); 76 n=strlen(s); 77 build_sa(256); 78 build_height(); 79 int top=0; 80 re(i,0,n-1) 81 { 82 while(top&&h[sta[top]]>=h[i])top--; 83 l[i]=(top?sta[top]+1:0); 84 sta[++top]=i; 85 } 86 top=0; 87 rre(i,n-1,0) 88 { 89 while(top&&h[sta[top]]>h[i])top--; 90 r[i]=(top?sta[top]-1:n-1); 91 sta[++top]=i; 92 } 93 ans+=(LL)(1+n)*n/2*(n-1); 94 re(i,0,n-1) 95 ans-=2LL*(i-l[i]+1)*(r[i]-i+1)*h[i]; 96 printf("%lld",ans); 97 return 0; 98 }