Pagini recente » Cod sursa (job #1764208) | Cod sursa (job #2572026) | Cod sursa (job #638896) | Cod sursa (job #667294) | Cod sursa (job #3233344)
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
const int P = 31;
const int MOD = 1e9 + 7;
// Function to calculate hash values for all substrings of a given length
bool check(const string& text, int length, int K) {
int n = text.size();
long long hash = 0;
long long p_pow = 1;
vector<long long> p_powers(n);
p_powers[0] = 1;
for (int i = 1; i < n; ++i) {
p_powers[i] = (p_powers[i-1] * P) % MOD;
}
for (int i = 0; i < length; ++i) {
hash = (hash * P + text[i]) % MOD;
}
unordered_map<long long, int> hash_count;
hash_count[hash]++;
for (int i = length; i < n; ++i) {
hash = (hash - text[i - length] * p_powers[length - 1] % MOD + MOD) % MOD;
hash = (hash * P + text[i]) % MOD;
hash_count[hash]++;
}
for (const auto& entry : hash_count) {
if (entry.second >= K) {
return true;
}
}
return false;
}
int longestKRepeatedSubstring(const string& text, int K) {
int left = 1, right = text.size();
int result = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (check(text, mid, K)) {
result = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
int main() {
ifstream infile("substr.in");
ofstream outfile("substr.out");
int N, K;
infile >> N >> K;
string text;
infile >> text;
int result = longestKRepeatedSubstring(text, K);
outfile << result << endl;
infile.close();
outfile.close();
return 0;
}