Cod sursa(job #325320)

Utilizator ProtomanAndrei Purice Protoman Data 19 iunie 2009 23:54:14
Problema Substr Scor 60
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.45 kb
#include <algorithm>
#include <stdio.h>
#include <vector>

#define MAX 32000
#define pb push_back
#define mp make_pair
#define f first
#define s second

using namespace std;

int n, k, lgn;
int vctSor[MAX], dp[MAX];
int matPos[16][MAX];
char strCit[MAX];
pair <pair <int, int>, int> vctPer[MAX];

inline int lcp(int x, int y)
{
	int lung = 0;
	for (int k = lgn; k >= 0 && x <= n && y <= n; k--)
		if (matPos[k][x] == matPos[k][y])
			x += 1 << k, y += 1 << k, lung += 1 << k;

	return lung;
}

int main()
{
	freopen("substr.in", "r", stdin);
	freopen("substr.out", "w", stdout);

	scanf("%d %d\n", &n, &k);

	fgets(strCit + 1, MAX, stdin);

	for (int i = 1; i <= n; i++)
		matPos[0][i] = strCit[i] - '0';

	lgn = -1;
	for (int pas = 1, cnt = 0; cnt >> 1 <= n; pas++, cnt = (!cnt)? 1 : cnt << 1, lgn++)
	{
		for (int i = 1; i <= n; i++)
			vctPer[i] = mp(mp(matPos[pas - 1][i], matPos[pas - 1][i + cnt]), i);

		if (!cnt)
			pas--;

		sort(vctPer + 1, vctPer + 1 + n);

		for (int i = 0; i < n; i++)
			if (vctPer[i + 1].f == vctPer[i].f)
				dp[i + 1] = dp[i];
			else dp[i + 1] = dp[i] + 1;

		for (int i = 1; i <= n; i++)
			matPos[pas][vctPer[i].s] = dp[i];
	}

	for (int i = 1; i <= n; i++)
		vctSor[matPos[lgn][i]] = i;

	int maxGs = 0;
	for (int i = 1; i <= n - k + 1; i++)
		maxGs = max(maxGs, lcp(vctSor[i], vctSor[i + k - 1]));

	printf("%d\n", maxGs);

	fclose(stdin);
	fclose(stdout);
	return 0;
}