您的位置:首页 > 其它

poj3261(后缀数组--可重叠的k次最长重复子串+二分+离散化)

2015-09-04 16:29 429 查看
题目链接:点击打开链接

题意描述:给定一个字符串,找出可重叠k次的最长重复子串?

解题思路:后缀数组+二分+离散化

代码:

#include <cstdio>
#include <algorithm>
#include <iostream>
#define maxn 20010
using namespace std;
int wa[maxn],wb[maxn],wv[maxn],ww[maxn];
int cmp(int* r,int a,int b,int l)
{
return r[a]==r[b]&&r[a+l]==r[b+l];
}
void da(int* r,int *sa,int n,int m)
{
int i,j,p,*x=wa,*y=wb,*t;
for(i=0; i<m; ++i) ww[i]=0;
for(i=0; i<n; ++i) ww[x[i]=r[i]]++;
for(i=1; i<m; ++i) ww[i]+=ww[i-1];
for(i=n-1; i>=0; i--) sa[--ww[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) ww[i]=0;
for(i=0; i<n; ++i) ww[wv[i]]++;
for(i=1; i<m; i++) ww[i]+=ww[i-1];
for(i=n-1; i>=0; --i) sa[--ww[wv[i]]]=y[i];
for(t=x,x=y,y=t,p=1,x[sa[0]]=0,i=1; i<n; ++i)
x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;
}
return ;
}
int ranks[maxn],height[maxn];
void calheight(int* r,int* sa,int n)
{
int i,j,k=0;
for(i=1; i<=n; ++i) ranks[sa[i]]=i;
for(i=0; i<n; height[ranks[i++]]=k)
for(k?k--:0,j=sa[ranks[i]-1]; r[i+k]==r[j+k]; k++);
return;
}
int sa[maxn];
int check(int n,int k,int cc)
{
int x=0;
for(int i=2; i<=n; ++i)
{
if(height[i]<k) x=0;
else
{
x=(x==0?2:(x+1));
if(x>=cc) return true;
}
}
return false;
}
struct node
{
int v;
int id;
int rk;
} st[maxn];
bool cmp1(node a,node b){
return a.v<b.v;
}
bool cmp2(node a,node b){
return a.id<b.id;
}
int n,str[maxn],cc;
int main()
{
while(scanf("%d%d",&n,&cc)!=EOF)
{
for(int i=0; i<n; ++i)
{
scanf("%d",&st[i].v);
st[i].id=i;
}
sort(st,st+n,cmp1);
st[0].rk=1;
int m=2;
for(int i=1; i<n; ++i)
{
if(st[i].v==st[i-1].v)
st[i].rk=st[i-1].rk;
else
st[i].rk=m++;
}
sort(st,st+n,cmp2);
for(int i=0;i<n;++i) str[i]=st[i].rk;
str
=0;
da(str,sa,n+1,m);
calheight(str,sa,n);
int l=0,r=n;
int ans=0;
while(l<=r)
{
int mid=(l+r)>>1;
if(check(n,mid,cc))
{
l=mid+1;
ans=max(mid,ans);
}
else
r=mid-1;
}
printf("%d\n",ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: