CF802I Fake News (hard)【后缀自动机】

传送门
每个点代表的不同子串个数就是 \(len[x]-len[fa[x]]\),没必要再在 DAG 上统计从 \(1\)\(x\) 的路径数了。
当然每个点代表的子串出现次数就是 \(endpos\) 值,可以建 \(parent\) 树 dfs,也可以直接按 \(len\) 排序,形成拓扑序列,然后累加。

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e5+10;
int n;
char s[N];
LL ans;
struct SuffixAutoMachine{
	int last,tot,ch[N*2][26],fa[N*2],len[N*2],epos[N*2],cnt[N*2],c[N*2],a[N*2];
	int newnode(int id){fa[++tot]=fa[id];len[tot]=len[id];memcpy(ch[tot],ch[id],sizeof(ch[tot]));return tot;}
	void insert(int c){
		int p=last,np=last=newnode(0);
		len[np]=len[p]+1;epos[np]=1;
		for(;p&&!ch[p][c];p=fa[p]) ch[p][c]=np;
		if(!p) {fa[np]=1;return;}
		int q=ch[p][c];
		if(len[q]==len[p]+1) {fa[np]=q;return;}
		int nq=newnode(q);len[nq]=len[p]+1;epos[nq]=0;
		fa[q]=fa[np]=nq;
		for(;p&&ch[p][c]==q;p=fa[p]) ch[p][c]=nq;
	}
	void init(){
		last=tot=0;
		last=newnode(0);
		for(int i=1;i<=n;i++) insert(s[i]-'a');
		memset(c,0,sizeof(c));
		memset(cnt,0,sizeof(cnt));
		for(int i=1;i<=tot;i++) c[len[i]]++;
		for(int i=1;i<=tot;i++) c[i]+=c[i-1];
		for(int i=tot;i>=1;i--) a[c[len[i]]--]=i;
		cnt[1]=1;
		for(int i=1;i<=tot;i++){
			int u=a[i];
			for(int j=0;j<26;j++) if(ch[u][j]) cnt[ch[u][j]]+=cnt[u];
		}
		for(int i=tot;i>=2;i--) epos[fa[a[i]]]+=epos[a[i]];
		for(int i=2;i<=tot;i++) ans+=1ll*epos[i]*epos[i]*cnt[i];
	}
}sam;

void solve(){
	scanf("%s",s+1);
	n=strlen(s+1);
	ans=0;
	sam.init();
	printf("%lld\n",ans);
}

int main(){
	int T;scanf("%d",&T);
	while(T--) solve();
	return 0;
}

猜你喜欢

转载自www.cnblogs.com/BakaCirno/p/12670822.html