poj 2774
传送门:http://poj.org/problem?id=2774
裸的后缀数组,我只是为了贴个版而已
代码
#include <cstdio>
#include <cmath>
#include <iostream>
#include <cstring>
#include <algorithm>
#define ll long long
#define mod 1000000007
using namespace std;
int s[200005],wa[200005],wb[200005],ws1[200005],sz[200005],wv[200005],rank[200005],sa[200005],height[200005];
char s1[200005],s2[200005];
bool cmp(int *x,int a,int b,int k)
{
return (x[a]==x[b])&&(x[a+k]==x[b+k]);
}
void getsa(int *r,int *sa,int n,int m)
{
int i,j,p,*x=wa,*y=wb,*t;
for (i=0;i<m;i++) ws1[i]=0;
for (i=0;i<n;i++) ws1[x[i]=r[i]]++;
for (i=1;i<m;i++) ws1[i]+=ws1[i-1];
for (i=n-1;i>=0;i--) sa[--ws1[x[i]]]=i;
for (j=1,p=1;p<n;j*=2,m=p)
{
for (p=0,i=n-j;i<n;i++) y[p++]=i;
for (i=0;i<n;i++) if (sa[i]>=j)y[p++]=sa[i]-j;
for (i=0;i<n;i++) wv[i]=x[y[i]];
for (i=0;i<m;i++) ws1[i]=0;
for (i=0;i<n;i++) ws1[wv[i]]++;
for (i=1;i<m;i++) ws1[i]+=ws1[i-1];
for (i=n-1;i>=0;i--) sa[--ws1[wv[i]]]=y[i];
t=x;x=y;y=t;
x[sa[0]]=0;
for (p=1,i=1;i<n;i++)
{
x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;
}
}
return;
}
void getans(int *r,int n)
{
int i,j,k=0;
for (i=1;i<=n;i++) rank[sa[i]]=i;
for (i=0;i<n;i++)
{
if (k) k--;
else k=0;
j=sa[rank[i]-1];
while (r[i+k]==r[j+k])
{
k++;
}
height[rank[i]]=k;
}
return;
}
int main()
{
while (~scanf("%s",s1))
{
int t=0;
scanf("%s",s2);
int len=strlen(s1);
int x1=0;
for (int i=0;i<len;i++)
s[x1++]=s1[i]-'a'+1;
s[x1++]=28;
len=strlen(s2);
for (int i=0;i<len;i++)
s[x1++]=s2[i]-'a'+1;
s[x1]=0;
getsa(s,sa,x1+1,30);
getans(s,x1);
int ans=0;
len=strlen(s1);
for (int i=2;i<x1;i++)
if(height[i]>ans)
{
if(0<=sa[i-1]&&sa[i-1]<len&&len<sa[i])
ans=height[i];
if(0<=sa[i]&&sa[i]<len&&len<sa[i-1])
ans=height[i];
}
printf("%d\n",ans);
}
}