PAT (Top Level) Practise 1005 Programming Pattern (35)

时间:2021-04-06 17:33:23

后缀数组。排序之后得到height数组,然后从上到下将height>=len的都分为一组,然后找到第一组个数最多的输出即可。

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
typedef long long LL;
const double pi=acos(-1.0),eps=1e-;
void File()
{
freopen("D:\\in.txt","r",stdin);
freopen("D:\\out.txt","w",stdout);
}
inline int read()
{
char c = getchar(); while(!isdigit(c)) c = getchar();
int x = ;
while(isdigit(c)) { x = x * + c - ''; c = getchar(); }
return x;
} const int maxn=+; int wa[maxn],wb[maxn],wv[maxn],WS[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=; i<m; i++) WS[i]=;
for(i=; i<n; i++) WS[x[i]=r[i]]++;
for(i=; i<m; i++) WS[i]+=WS[i-];
for(i=n-; i>=; i--) sa[--WS[x[i]]]=i;
for(j=,p=; p<n; j*=,m=p)
{
for(p=,i=n-j; i<n; i++) y[p++]=i;
for(i=; i<n; i++) if(sa[i]>=j) y[p++]=sa[i]-j;
for(i=; i<n; i++) wv[i]=x[y[i]];
for(i=; i<m; i++) WS[i]=;
for(i=; i<n; i++) WS[wv[i]]++;
for(i=; i<m; i++) WS[i]+=WS[i-];
for(i=n-; i>=; i--) sa[--WS[wv[i]]]=y[i];
for(t=x,x=y,y=t,p=,x[sa[]]=,i=; i<n; i++)
x[sa[i]]=cmp(y,sa[i-],sa[i],j)?p-:p++;
}
return;
} int Rank[maxn],height[maxn];
void calheight(int *r,int *sa,int n)
{
int i,j,k=;
for(i=; i<=n; i++) Rank[sa[i]]=i;
for(i=; i<n; height[Rank[i++]]=k)
for(k?k--:,j=sa[Rank[i]-]; r[i+k]==r[j+k]; k++);
return;
} int T,n,a[maxn],SA[maxn],sum[maxn];
char str[maxn],op[]; int Find(int D,int l,int r)
{
int pos=-;
while(l<=r)
{
int mid=(l+r)/;
if(sum[mid]-D>) r=mid-;
else if(sum[mid]-D==) pos=mid,r=mid-;
else l=mid+;
}
return pos;
} int main()
{
int len; scanf("%d",&len); getchar();
gets(str); n=strlen(str);
for(int i=;i<n;i++) a[i]=(int)str[i];
a[n]=; da(a,SA,n+,); calheight(a,SA,n);
int L=,R=;
int ansL,ansR,ans=;
while()
{
if(height[R]>=len)
{
R++;
if(R-L+>ans) ans=R-L+, ansL = L, ansR = R;
}
else L=R+, R=L;
if(L>n||R>n) break;
}
for(int i=SA[ansL];i<=SA[ansL]+len-;i++) printf("%c",str[i]);
printf(" %d\n",ans);
return ;
}