Cod sursa(job #1227290)

Utilizator iordache.bogdanIordache Ioan-Bogdan iordache.bogdan Data 9 septembrie 2014 20:44:42
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.63 kb
#include <fstream>
#include <cstring>
#include <algorithm>
#define DLOG 17
#define DIM 17000

using namespace std;

ifstream f("substr.in");
ofstream g("substr.out");

struct data {
	int n0, n1;
	int pos;
} L[DIM];

char S[DIM];

int P[DLOG][DIM];

int n, k, cnt;

pair<int, int> V[DIM];

int maxim(int a, int b) {
	return (a>b ? a : b);
}

bool cmp(const data &a, const data &b) {
	return (a.n0 == b.n0 ? a.n1 < b.n1 : a.n0 < b.n0);
}

int LCP(int x, int y) {
	if (x == y)
		return n - x;
	int ans = 0;
	for (int pow = cnt; pow >= 0 && x < n && y < n; --pow)
	if (P[pow][x] == P[pow][y]) {
		x += (1 << pow);
		y += (1 << pow);
		ans += (1 << pow);
	}
	return ans;
}

int main() {
	f >> n >> k;
	f.ignore(10, '\n');
	f.getline(S, DIM);
	for (int i = 0; S[i] != 0; ++i)
	if (S[i] >= 'a' && S[i] <= 'z')
		P[0][i] = S[i] - 'a';
	else
	if (S[i] >= 'A' && S[i] <= 'Z')
		P[0][i] = S[i] - 'A' + 26;
	else
		P[0][i] = S[i] - '0' + 52;
	int pow;
	for (cnt = 1, pow = 1; (pow >> 1) < n; pow <<= 1, ++cnt) {
		for (int i = 0; i < n; ++i) {
			L[i].pos = i;
			L[i].n0 = P[cnt - 1][i];
			L[i].n1 = (i + pow < n) ? P[cnt - 1][i + pow] : -1;
		}
		sort(L, L + n, cmp);
		for (int i = 0; i < n; ++i)
		if (i>0 && L[i - 1].n0 == L[i].n0 && L[i - 1].n1 == L[i].n1)
			P[cnt][L[i].pos] = P[cnt][L[i - 1].pos];
		else
			P[cnt][L[i].pos] = i;
	}
	--cnt;
	for (int i = 0; i < n; ++i) {
		V[i].first = P[cnt][i];
		V[i].second = i;
	}
	sort(V, V + n);
	int Max = 0;
	for (int i = 0; i <= n - k; ++i) {
		int aux = LCP(V[i].second, V[i + k - 1].second);
		Max = maxim(Max, aux);
	}
	g << Max;
	return 0;
}