Longest Common Substring SPOJ - LCS

题目大意:给你两个字符串,让你找到他们的最长公共子串的长度

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 250000  + 10;
const int CHAR = 28;
struct SAM_Node
{
    SAM_Node *fa,*next[CHAR];
    int len;
    int id,pos;
    SAM_Node(){}
    SAM_Node(int l)
    {
        fa=0;
        len=l;
        memset(next,0,sizeof(next));
    }
} ;
SAM_Node SAM_node[maxn*2],*SAM_rot,*SAM_last;
int SAM_size;
SAM_Node *newSAM_Node(int len)
{
    SAM_node[SAM_size]=SAM_Node(len);
    SAM_node[SAM_size].id=SAM_size;
    return &SAM_node[SAM_size++];
}
SAM_Node *newSAM_Node(SAM_Node *p)
{
    SAM_node[SAM_size]=*p;
    SAM_node[SAM_size].id=SAM_size;
    return &SAM_node[SAM_size++];
}
void SAM_init()
{
    SAM_size=0;
    SAM_rot=SAM_last=newSAM_Node(0);
    SAM_node[0].pos=0;
}
void SAM_add(int x,int len)
{
    SAM_Node *p=SAM_last,*np=newSAM_Node(p->len+1);
    np->pos=len;
    SAM_last=np;
    for(;p&&!p->next[x];p=p->fa)
    {
        p->next[x]=np;
    }
    if(!p)
    {
        np->fa=SAM_rot;
        return ;
    }
    SAM_Node *q = p->next[x];
    if(q->len==p->len+1)
    {
        np->fa=q;
        return ;
    }
    SAM_Node *nq=newSAM_Node(q);
    nq->len=p->len+1;
    q->fa=nq;
    np->fa=nq;
    for(;p&&p->next[x]==q;p=p->fa)
    {
        p->next[x]=nq;
    }
}
char s1[maxn],s2[maxn];
int main()
{
    while(~scanf("%s",s1))
    {
        scanf("%s",s2);
        SAM_init();
        int len1=strlen(s1);
        int len2=strlen(s2);
        for(int i=0;i<len1;i++)
            SAM_add(s1[i]-'a',i+1);
        int ans = 0;
        SAM_Node *p = SAM_rot;
        int num = 0;
        for(int i=0;i<len2;i++)
        {
            int x = s2[i]-'a';
           // cout<
            if(p->next[x])
            {
                num = num + 1;
                p = p->next[x];
              //  cout<<444<<" "<
            }
            else
            {
               // cout<
                while(p&&p->next[x]==0) p = p->fa;
               // cout<
                if(!p)
                {
                    num = 0;
                    p = SAM_rot;
                }
                else{
                    num = p->len + 1;
                    p = p->next[x];
                }
            }
            ans = max(ans,num);
        }
        printf("%d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(字符串)