[BZOJ3238][AHOI2013]差异

bzoj
luogu
题意:给出一个长度为n的字符串,求

\[\sum_{1\le{i}<{j}\le{n}}len(T_i)+len(T_j)-2lcp(T_i,T_j) \]

sol

做完NOI2015品酒大会回来这题就是道思博题啊
按照\(Height\)从大往小合并两个\(Rank\)相邻的后缀,每次更新答案
这样直接求出来的是$$\sum_{1\le{i}<{j}\le{n}}lcp(T_i,T_j)$$
所以说为什么要给一个长成那个样子的式子啊
设上面求出来的答案为\(ans\),那么输出\(\frac{n(n+1)(n-1)}{2}-2*ans\)

code

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
int gi()
{
    int x=0,w=1;char ch=getchar();
    while ((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
    if (ch=='-') w=0,ch=getchar();
    while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
    return w?x:-x;
}
const int N = 5e5+5;
char s[N];
int n,a[N],t[N],x[N],y[N],SA[N],Rank[N],Height[N],id[N],fa[N],sz[N];
ll ans;
bool cmp(int i,int j,int k){return y[i]==y[j]&&y[i+k]==y[j+k];}
void getSA()
{
	int m=30;
	for (int i=1;i<=n;++i) ++t[x[i]=a[i]];
	for (int i=1;i<=m;++i) t[i]+=t[i-1];
	for (int i=n;i>=1;--i) SA[t[x[i]]--]=i;
	for (int k=1;k<=n;k<<=1)
	{
		int p=0;
		for (int i=0;i<=m;++i) y[i]=0;
		for (int i=n-k+1;i<=n;++i) y[++p]=i;
		for (int i=1;i<=n;++i) if (SA[i]>k) y[++p]=SA[i]-k;
		for (int i=0;i<=m;++i) t[i]=0;
		for (int i=1;i<=n;++i) ++t[x[y[i]]];
		for (int i=1;i<=m;++i) t[i]+=t[i-1];
		for (int i=n;i>=1;--i) SA[t[x[y[i]]]--]=y[i];
		swap(x,y);
		x[SA[1]]=p=1;
		for (int i=2;i<=n;++i) x[SA[i]]=cmp(SA[i],SA[i-1],k)?p:++p;
		if (p>=n) break;m=p;
	}
	for (int i=1;i<=n;++i) Rank[SA[i]]=i;
	for (int i=1,j=0;i<=n;++i)
	{
		if (j) --j;
		while (a[i+j]==a[SA[Rank[i]-1]+j]) ++j;
		Height[Rank[i]]=j;
	}
}
int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
void merge(int x,int y,int h)
{
	x=find(x);y=find(y);
	ans+=1ll*sz[x]*sz[y]*h;
	sz[x]+=sz[y];fa[y]=x;
}
bool comp(int i,int j){return Height[i]>Height[j];}
int main()
{
	scanf("%s",s+1);n=strlen(s+1);
	for (int i=1;i<=n;++i) a[i]=s[i]-'a'+1;
	getSA();
	for (int i=1;i<=n;++i) fa[i]=i,sz[i]=1;
	for (int i=2;i<=n;++i) id[i]=i;
	sort(id+2,id+n+1,comp);
	for (int i=2;i<=n;++i)
		merge(SA[id[i]-1],SA[id[i]],Height[id[i]]);
	printf("%lld\n",1ll*n*(n+1)*(n-1)/2-2*ans);
	return 0;
}
posted @ 2018-02-26 14:26  租酥雨  阅读(121)  评论(0编辑  收藏  举报