Cod sursa(job #712309)

Utilizator antoanelaAntoanela Siminiuc antoanela Data 13 martie 2012 12:08:55
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.16 kb
#include <cstdio>
#include <algorithm>
using namespace std;
#define nmax 16390

char s[nmax];
int n, k, p[20][nmax], ans, u[nmax], c[nmax], u2[nmax], step;

struct nr
{
	int x, y, p;
} v[nmax];

int cmp (nr a, nr b)
{
	if (a.x == b.x) return a.y<b.y;
	return a.x<b.x;
}

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

int main()
{
	freopen("substr.in","r",stdin);
	freopen("substr.out","w",stdout);
	scanf("%d %d\n", &n, &k);
	int i, cnt;
	fgets(s, nmax, stdin);
	for (i=0; i<n; i++) p[0][i] = s[i] - 'a';
	for (step=1, cnt=1; (cnt>>1) <n; step++, cnt<<=1)
	{
		for (i=0; i<n; i++)
		{
			v[i].x = p[step-1][i];
			if (i+cnt<n) v[i].y = p[step-1][i+cnt]; else
				v[i].y = -1;
			v[i].p = i;
		}
		sort (v, v+n, cmp);
		for (i=0; i<n; i++)
			if (v[i].x == v[i-1].x && v[i].y == v[i-1].y)
				p[step][v[i].p] = p[step][v[i-1].p]; else
				p[step][v[i].p] = i;
	}
	
	for (i=0; i<n-k+1; i++) 
		ans=max(ans, lcp(v[i].p, v[i+k-1].p));
	printf("%d\n",ans);
}