Cod sursa(job #1053598)

Utilizator ELHoriaHoria Cretescu ELHoria Data 12 decembrie 2013 20:43:34
Problema Substr Scor 100
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 0.96 kb
#include <fstream>
#include <unordered_map>
#include <string>
#include <cstring>

using namespace std;

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

const int mod = 16385000;
int N, K;
char str[1 << 15];

bool isGood(int L) {
	unordered_map<int, int> H;
	int hash = 0;
	int X = 1;
	for (int i = 0; i < L; i++) {
		hash = ((hash << 5) + hash + str[i]) % mod;
		X = ((X << 5) + X) % mod;
	}
	
	H[hash] = 1;
	if (K == 1) return true;
	for (int i = L; i < N; i++) {
		hash = ((hash << 5) + hash + str[i]) % mod;
		hash -= (X * str[i - L]) % mod;
		if (hash < 0) 
			hash += mod;
		if (++H[hash] >= K) {
			return true;
		}
	}
	return false;
}

int main()
{
	cin >> N >> K >> str;
	if (K == 1) {
		cout << N;
		return 0;
	}

	int ans = 0;
	int l = 0, r = N;
	while (l <= r) {
		int mid = (l + r) / 2;
		if (isGood(mid)) {
			l = mid + 1;
			ans = mid;
		} else {
			r = mid - 1;
		}
	}

	cout << ans;
	return 0;
}