Cod sursa(job #355714)

Utilizator GheorgheMihaiMihai Gheorghe GheorgheMihai Data 11 octombrie 2009 22:31:19
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.07 kb
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct entry
{
	int x,y,p;
};
char s[16390];
int p[17][16390];
entry l[16390];
int n,d,step;

bool cmp(entry a, entry b)
{
	if(a.x<b.x || (a.x==b.x && a.y<b.y))
		return 1;
	return 0;
}

int lcp(int x, int y, int step)
{
	if(x==y)
		return n-x;
	int i,ret=0;
	for(i=step-1;x<n && y<n && i>=0;--i)
		if( p[i][x]==p[i][y])
		{
			x+=1<<i;
			y+=1<<i;
			ret+=1<<i;
		}
	return ret;
}

int main()
{
	freopen("substr.in","r",stdin);
	freopen("substr.out","w",stdout);
	scanf("%d%d\n",&n,&d);
	gets(s);
	int i,j,step;
	for(i=0;i<n;i++)
		p[0][i]=s[i]-'a';
	for(j=1,step=1;(j<<1)<n;j=j<<1,step++)
	{
		for(i=0;i<n;i++)
		{
			l[i].x=p[step-1][i];
			l[i].y=p[step-1][i+j];
			l[i].p=i;
		}
		sort(l,l+n,cmp);
		p[step][l[0].p]=0;
		for(i=1;i<n;i++)
			p[step][l[i].p]=l[i].x==l[i-1].x && l[i].y==l[i-1].y?p[step][l[i-1].p]:i;
	}
	int sol=0,x;
	for(i=0;i<=n-d;i++)
	{
		x=lcp(l[i].p,l[i+d-1].p,step);
		if(x>sol)
			sol=x;
	}
	printf("%d\n",sol);
	return 0;
}