Cod sursa(job #627935)

Utilizator andra23Laura Draghici andra23 Data 30 octombrie 2011 23:38:36
Problema Substr Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.18 kb
#include<iostream>
#include<fstream>
#include<tr1/unordered_map>

using namespace std;
using namespace tr1;

const int MAXN = 16390;
const int MOD = 66601373;
const int B = 29;
char s[MAXN];
unordered_map <int,int> h;

int testSolution(int l, int n, int k) {
	int strValue = 0;
	int m = 1;
	h.clear();
	for (int i = 0; i < l; i++) {
		strValue = (strValue*B + (s[i]-'a')) % MOD;
		m = (m*B) % MOD;
	}
	h[strValue] = 1;
	if (k == 1) {
		return 1;
	}

	for (int i = l; i < n; i++) {
		strValue = (strValue*B +(s[i]-'a')) % MOD;
		strValue -= ((s[i-l]-'a')*m) % MOD;
		if (strValue < 0) {
			strValue += MOD;
		}
		unordered_map<int,int>::iterator it = h.find(strValue);
		if (it != h.end()) {
			it->second++;
			if (it->second >= k) {
				return 1;
			}
		} else {
			h[strValue] = 1;
		}
	}

	return 0;
}

int bsearch(int left, int right, int n, int k) {
	int m, result = 0;
	while (left <= right) {
		m = (left+right)/2;
		if (testSolution(m, n, k)) {
			result = m;
			left = m+1;
		} else {
			right = m-1;
		}
	}
	return result;
}

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

	int n, k;
	f >> n >> k;
	f >> s;

	int result = bsearch(0, n/k, n, k);

	g << result << '\n';

	return 0;
}