Cod sursa(job #1053491)

Utilizator ELHoriaHoria Cretescu ELHoria Data 12 decembrie 2013 19:45:26
Problema Substr Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.34 kb
#include <fstream>
#include <unordered_map>
#include <string>

using namespace std;

ifstream cin("substr.in");
ofstream cout("substr.out");

const int nmax = 20000;
const int mod = 2007079397;
const int A_ = 131;
int N, K;
string str;
int h[nmax];
int INV[nmax];
unordered_map<int, int> H;

inline int getIndex(char x) {
	return x - 'a' + 13;
}

int logpow(int a, int b) {
	int ret = 1;
	for (; b > 0; b >>= 1, a = 1LL * a * a % mod) {
		if (b & 1) {
			ret = 1LL * ret * a % mod;
		}
	}
	return ret;
}

void compute() {
	int X = A_;
	h[1] = getIndex(str[0]);
	INV[0] = 1;
	for (int i = 2; i <= N; i++, X = 1LL * X * A_ % mod) {
		h[i] = (1LL * h[i - 1] + 1LL * X * getIndex(str[i - 1])) % mod;
		INV[i - 1] = logpow(X, mod - 2);
	}
}

inline int getHash(int l, int r) {
	return 1LL * (1LL * h[r] - h[l - 1] + mod) * INV[l - 1] % mod;
}

bool isGood(int L) {
	int hash;
	H.clear();
	for (int i = 1; i + L - 1 <= N; i++) {
		hash = getHash(i, i + L - 1);
		if (++H[hash] == K) {
			return true;
		}
	}
	return false;
}

int main()
{
	cin >> N >> K;
	if (K == 1) {
		cout << N;
		return 0;
	}
	cin.get();
	getline(cin, str);
	compute();
	int ans = 0;
	for (int step = 1 << 15; step > 0; step >>= 1) {
		if (step + ans <= N && isGood(step + ans)) {
			ans += step;
		}
	}
	cout << ans;
	return 0;
}