Cod sursa(job #325051)

Utilizator AndreyPAndrei Poenaru AndreyP Data 18 iunie 2009 17:30:34
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.26 kb
#include<cstdio>
#include<algorithm>
using namespace std;
#define fs first
#define sc second
#define mp make_pair
#define N 16400
#define LG 16
struct entry
{
	pair<int,int> nr;
	int p;
};
entry l[N];
int p[LG][N],n,k,lim;
char c[N];
bool compar(const entry &x,const entry &y)
{
	if(x.nr<y.nr)
		return true;
	return false;
}
inline int lcp(int x,int y)
{
	int ret=0;
	if(x==y)
		return n-x;
	for(int i=lim; i>=0 && x<n && y<n; --i)
	{
		if(p[i][x]==p[i][y])
		{
			int aux=1<<i;
			x+=aux;
			y+=aux;
			ret+=aux;
		}
	}
	return ret;
}
int main()
{
	freopen("substr.in","r",stdin);
	freopen("substr.out","w",stdout);
	scanf("%d%d\n",&n,&k);
	fgets(c,N,stdin);
	for(int i=0; i<n; ++i)
		p[0][i]=c[i]-'0';
	for(int stp=1,cnt=1; (cnt>>1)<n; ++stp,cnt<<=1)
	{
		for(int i=0; i<n; ++i)
		{
			l[i].nr.fs=p[stp-1][i];
			l[i].nr.sc=(i+cnt<n) ? p[stp-1][i+cnt] : -1;
			l[i].p=i;
		}
		sort(l,l+n,compar);
		int ind=0;
		p[stp][l[0].p]=0;
		for(int i=1; i<n; ++i)
		{
			if(l[i].nr.fs!=l[i-1].nr.fs || l[i].nr.sc!=l[i-1].nr.sc)
				++ind;
			p[stp][l[i].p]=ind;
		}
		lim=stp;
	}
	int rez=0;
	for(int i=0; i+k-1<n; ++i)
	{
		int aux=lcp(l[i].p,l[i+k-1].p);
		if(aux>rez)
			rez=aux;
	}
	printf("%d\n",rez);
	return 0;
}