Cod sursa(job #3324651)

Utilizator Ruxandra009Ruxandra Vasilescu Ruxandra009 Data 22 noiembrie 2025 19:45:59
Problema Substr Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.4 kb
#include <algorithm>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int inf = 1e9;

const string txt = "data", file = "substr";
const int nmax = 20000;

ifstream f(file + ".in");
ofstream g(file + ".out");

struct ceva {
	int a, b, ind;
} aux[nmax];

int n, k, p[20][nmax], ans[nmax], nr;
char s[nmax];

bool cmp(ceva x, ceva y) {
	return (x.a != y.a ? x.a < y.a : x.b < y.b);
}

int lcp(int x, int y)
{
	if (x == y) return n - x + 1;
	int lg = 0;
	for (int i = nr; i >= 0 && x <= n && y <= n; i--)
	{
		if (p[i][x] != p[i][y]) continue;

		lg += (1 << i);
		x += (1 << i);
		y += (1 << i);
	}

	return lg;
}

int main()
{
	f >> n >> k;
	
	for (int i = 1; i <= n; i++) {
		f >> s[i];
		p[0][i] = s[i] - 'a' + 1;
	}

	for (int j = 1; (1 << (j - 1)) <= n; j++)
	{
		nr ++;
		for (int i = 1; i <= n; i++)
		{
			aux[i].a = p[j - 1][i]; aux[i].ind = i;
			if (i + (1 << (j - 1)) <= n)
				aux[i].b = p[j - 1][i + (1 << (j - 1))];
			else aux[i].b = 0;
		}

		sort(aux + 1, aux + n + 1, cmp);

		int cnt = 0;
		for (int i = 1; i <= n; i++)
		{
			if (aux[i].a != aux[i - 1].a || aux[i].b != aux[i - 1].b) cnt++;
			p[j][aux[i].ind] = cnt;
		}
	}

	for (int i = 1; i <= n; i++)
		ans[p[nr][i]] = i;

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

	g << maxi;
	return 0;
}