[SPOJ-LCS]Longest Common Substring

vjudge

题意

求两个串的最长公共子串

sol

一个串建SAM,另一个串在SAM上跑匹配。
每次维护一下当前的最长长度就可以了。

code

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 5e5+5;
int n,last=1,tot=1,tr[N][26],fa[N],len[N],ans;
char s[N];
void extend(int c)
{
	int v=last,u=++tot;last=u;
	len[u]=len[v]+1;
	while (v&&!tr[v][c]) tr[v][c]=u,v=fa[v];
	if (!v) fa[u]=1;
	else
	{
		int x=tr[v][c];
		if (len[x]==len[v]+1) fa[u]=x;
		else
		{
			int y=++tot;
			memcpy(tr[y],tr[x],sizeof(tr[y]));
			fa[y]=fa[x];fa[x]=fa[u]=y;len[y]=len[v]+1;
			while (v&&tr[v][c]==x) tr[v][c]=y,v=fa[v];
		}
	}
}
int main()
{
	scanf("%s",s+1);n=strlen(s+1);
	for (int i=1;i<=n;++i) extend(s[i]-'a');
	scanf("%s",s+1);n=strlen(s+1);
	for (int i=1,now=1,cnt=0;i<=n;++i)
	{
		int c=s[i]-'a';
		if (tr[now][c]) ++cnt,now=tr[now][c];
		else
		{
			while (now&&!tr[now][c]) now=fa[now];
			if (!now) cnt=0,now=1;
			else cnt=len[now]+1,now=tr[now][c];
		}
		ans=max(ans,cnt);
	}
	printf("%d\n",ans);
	return 0;
}
posted @ 2018-03-27 21:22  租酥雨  阅读(146)  评论(0编辑  收藏  举报