Cod sursa(job #712295)

Utilizator antoanelaAntoanela Siminiuc antoanela Data 13 martie 2012 11:50:38
Problema Substr Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.62 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];

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 main()
{
	freopen("substr.in","r",stdin);
	freopen("substr.out","w",stdout);
	scanf("%d %d\n", &n, &k);
	int i, step, cnt, ok, prev, sprev, x;
	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;
	}
	
	prev=sprev=0;
	for (step=1, cnt=1; (cnt>>1) < n; cnt<<=1, step++);
	cnt--; step--;
	for (i=0; i<n; i++) u[i]=1;
	for (ans=0; cnt>=0; cnt >>= 1, step--)
	{
		for (i=0; i<n; i++) c[i]=0;
		for (i=0; i<n; i++)
		{
			v[i].x = p[sprev][i];
			if (i+prev < n) v[i].y = p[step][i+prev]; else
				v[i].y = -1;
			v[i].p=i;
		}
		sort (v, v+n, cmp);
		
		x=1;
		ok=0;
		for (i=1; i<n; i++) 
			if (v[i].x==v[i-1].x && v[i].y==v[i-1].y)
			{
				x++;
				if (x>=k) ok=1;
			} else x=1;
		
		if (ok)
		{
			sprev=step;
			prev=cnt*2;
			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;
			ans+=(1<<step);
		}
		if (!cnt) break;
	}
	printf("%d\n",ans);
}