【bzoj3238】 Ahoi2013—差异
http://www.lydsy.com/JudgeOnline/problem.php?id=3238 (题目链接)
题意
给出一个字符串,求${\sum_{1<=i<j<=n} len(T_i)+len(T_j)-2*lcp(T_i,T_j)}$,其中${T_i}$表示i的后缀
Solution
很简单,求个后缀数组,然后单调栈扫一遍就可以了。
细节
开LL
代码
// bzoj3238 #include<algorithm> #include<iostream> #include<cstdlib> #include<cstring> #include<cstdio> #include<cmath> #include<ctime> #define LL long long #define inf 1<<30 #define Pi acos(-1.0) #define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout); using namespace std; const int maxn=500010; int sa[maxn],rank[maxn],height[maxn],n; char s[maxn]; struct data {LL w,c;}st[maxn]; namespace Suffix { int wa[maxn],wb[maxn],ww[maxn]; bool cmp(int *r,int a,int b,int l) { return r[a]==r[b] && r[a+l]==r[b+l]; } void da(char *r,int *sa,int n,int m) { int i,j,p,*x=wa,*y=wb; for (i=0;i<=m;i++) ww[i]=0; for (i=1;i<=n;i++) ww[x[i]=r[i]]++; for (i=1;i<=m;i++) ww[i]+=ww[i-1]; for (i=n;i>=1;i--) sa[ww[x[i]]--]=i; for (p=0,j=1;p<n;j*=2,m=p) { for (p=0,i=n-j+1;i<=n;i++) y[++p]=i; for (i=1;i<=n;i++) if (sa[i]>j) y[++p]=sa[i]-j; for (i=0;i<=m;i++) ww[i]=0; for (i=1;i<=n;i++) ww[x[y[i]]]++; for (i=1;i<=m;i++) ww[i]+=ww[i-1]; for (i=n;i>=1;i--) sa[ww[x[y[i]]]--]=y[i]; for (swap(x,y),p=x[sa[1]]=1,i=2;i<=n;i++) x[sa[i]]=cmp(y,sa[i-1],sa[i],j) ? p : ++p; } } void calheight(char *r,int *sa,int n) { for (int i=1;i<=n;i++) rank[sa[i]]=i; for (int k=0,i=1;i<=n;i++) { if (k) k--; int j=sa[rank[i]-1]; while (r[i+k]==r[j+k]) k++; height[rank[i]]=k; } } } int main() { scanf("%s",s+1); int n=strlen(s+1); Suffix::da(s,sa,n,300); Suffix::calheight(s,sa,n); LL S=0,ans=0;int top=0; for (int i=1;i<=n;i++) ans+=(LL)(n-1)*i; for (int i=1;i<=n;i++) { ans-=S*2; while (top>1 && height[i+1]<st[top-1].w) { S-=(LL)(st[top].w-st[top-1].w)*st[top].c; st[top-1].c+=st[top].c; st[top--]=(data){0,0}; } if (height[i+1]<st[top].w) { S-=(LL)(st[top].w-height[i+1])*st[top].c; st[top].w=height[i+1]; } if (st[top].w==height[i+1]) st[top].c++,S+=height[i+1]; else st[++top]=(data){height[i+1],1},S+=height[i+1]; } printf("%lld",ans); return 0; }
This passage is made by MashiroSky.