题意:
就是求LCS
思路:
topsort后
每个父亲节点加上子节点的状态就行了吧
至于为什么传给父亲节点
这里Sam里的每个节点有个性质
假设当前节点的len==6,当前节点的pre节点len==2
这个节点接收的状态就是以当前节点为最后一个字符的后缀的长度是3~6里
比如当前节点的最长后缀是abcabb(sam.len==6),pre节点是b(sam.len==2)
那么当前节点的接收子串是abcabb,bcabb,cabb,abb
pre节点接收的状态就是bb,b
所以当前节点的状态包含pre节点
当前节点的状态包含pre节点的状态,所以当前节点的状态出现一次,pre节点的状态自然出现一次
至于后缀自动机的基本东西,很多东西都写在之前有一个Sam的解释里了
http://blog.youkuaiyun.com/qq_27925701/article/details/51347086
PS:
前几天学组合数学的题的时候好懒…懒得写题解了
因为那些题思路性很强,代码确实无聊
而且思路想到就想到了….
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<map>
#include<set>
using namespace std;
#define lowbit(x) (x&(-x))
typedef long long LL;
const int maxn = 250005;
const int inf=(1<<28)-1;
struct sam_node
{
int fa,son[26];
int len;
void init(int _len)
{
len=_len;fa=-1;
memset(son,-1,sizeof(son));
}
};
class SAM
{
public:
int root,last,tots;
sam_node sam[maxn*2];//length*2
SAM()
{
init();
}
void init()
{
tots=0;
root=last=0;
sam[tots].init(0);
}
void extend(char ch)
{
int w=ch-'a';
int p=last;
int np=++tots;sam[tots].init(sam[p].len+1);
int q,nq;while(p!=-1&&sam[p].son[w]==-1)
sam[p].son[w]=np,p=sam[p].fa;
if (p==-1) sam[np].fa=root;
else
{
q=sam[p].son[w];
if (sam[p].len+1==sam[q].len) sam[np].fa=q;
else
{
nq=++tots;sam[nq].init(0);
sam[nq]=sam[q];
sam[nq].len=sam[p].len+1;
sam[q].fa=nq;sam[np].fa=nq;
while(p!=-1&&sam[p].son[w]==q)
sam[p].son[w]=nq,p=sam[p].fa;
}
}
last=np;
}
void build(char* str)
{
int len=strlen(str);
for(int i=0;i<len;++i) extend(str[i]);
}
int r[maxn*2],w[maxn];
//r[i]为topsort后 入度为0先入队
void topsort()
{
int i,len=tots;
memset(w,0,sizeof(w));
for(int i=1;i<=tots;++i) w[sam[i].len]++;
for(int i=1;i<=len;++i) w[i]+=w[i-1];
for(int i=tots;i>=1;--i) r[w[sam[i].len]--]=i;
r[0]=0;
}
void output()
{
for(int i=0;i<=tots;++i)
{
printf("%d(fa=%d): ",i,sam[i].fa);
for(int j=0;j<26;++j)
if(sam[i].son[j]!=-1)
printf("%c(%d) ",j+'a',sam[i].son[j]);
printf("\n");
}
}
void Solve(char* str)
{
//output();
int len=strlen(str),p=root,Ans=0,tmp=0;
for(int i=0;i<len;++i)
{
int id=str[i]-'a';
while(sam[p].fa!=-1&&sam[p].son[id]==-1)
{
p=sam[p].fa;
tmp=sam[p].len;
}
if(sam[p].son[id]==-1)
{
tmp=sam[p].len;
}
else p=sam[p].son[id],tmp++;
//printf("%c-%d--%d ",str[i],p,tmp);
Ans=max(Ans,tmp);
}
printf("%d\n",Ans);
}
}Sam;
char str[maxn];
int main()
{
scanf("%s",str);
int len=strlen(str);
for(int i=0;i<len;++i)
Sam.extend(str[i]);
scanf("%s",str);
Sam.Solve(str);
return 0;
}