[SAM]BZOJ5137 [Usaco2017 Dec] Standing Out from the Herd

[title]
lydsy
Given nnn strings, for each string, ask how many substrings appear only in this string.
n,∑∣S∣≤105n,\sum|S|\leq 10^5n,∑∣S∣≤105

[solutions]
Write on the board.
After the generalized SAM\text{SAM}SAM is built, the right\text{right}right set can be merged from bottom to top. The implementation is to mark each end node with a color. If the marks are the same, it's better to set − 1-1 − 1.

The attempt to break the list failed.

[reference code]

#include<bits/stdc++.h>
using namespace std;

const int N=2e5+10;
int n,f[N],b[N],c[N];
long long ans[N];
char s[N];

struct SAM
{
	int sz,las,fa[N],mx[N],ch[N][26];
	void extend(int x)
	{
		int p,np,q,nq;
		if(ch[las][x])
		{
			p=las;las=q=ch[p][x];//be careful here, las=ch[p][x]
			if(mx[q]==mx[p]+1) return;
			las=nq=++sz;mx[nq]=mx[p]+1;
			memcpy(ch[nq],ch[q],sizeof(ch[q]));
			fa[nq]=fa[q];fa[q]=nq;
			for(;p && ch[p][x]==q;p=fa[p]) ch[p][x]=nq;
			return;
		}
		p=las;np=las=++sz;mx[np]=mx[p]+1;
		for(;p && !ch[p][x];p=fa[p]) ch[p][x]=np;
		if(!p) fa[np]=1;
		else
		{
			q=ch[p][x];
			if(mx[q]==mx[p]+1) fa[np]=q;
			else
			{
				nq=++sz;mx[nq]=mx[p]+1;
				memcpy(ch[nq],ch[q],sizeof(ch[q]));
				fa[nq]=fa[q];fa[q]=fa[np]=nq;
				for(;p && ch[p][x]==q;p=fa[p]) ch[p][x]=nq;
			}
		}
	}
	void merge()
	{
		for(int i=1;i<=sz;++i) b[mx[i]]++;
		for(int i=1;i<=sz;++i) b[i]+=b[i-1];
		for(int i=sz;i;--i) c[b[mx[i]]--]=i;
		for(int i=sz,x;i;--i)
		{
			x=c[i];
			if(~f[x]) ans[f[x]]+=mx[x]-mx[fa[x]];
			if(f[fa[x]] && f[fa[x]]!=f[x]) f[fa[x]]=-1; else f[fa[x]]=f[x];
		} 
	}
}T;

int main()
{
#ifdef Durant_Lee
	freopen("BZOJ5137.in","r",stdin);
	freopen("BZOJ5137.out","w",stdout);
#endif
	scanf("%d",&n);T.sz=1;
	for(int i=1;i<=n;++i)
	{
		T.las=1;scanf("%s",s+1);int len=strlen(s+1);
		for(int j=1;j<=len;++j) 
		{
			T.extend(s[j]-'a');
			if(!f[T.las]) f[T.las]=i; else f[T.las]=-1;
		}
	}
	T.merge();
	for(int i=1;i<=n;++i) printf("%lld",ans[i]),putchar('\n');
	return 0;
}

Posted by JayLewis on Sun, 24 Nov 2019 09:58:11 -0800